简体   繁体   中英

Silence output in bash script using function advisable?

Suppose, someone is writing bash script in which it is needed to silent stdout,stderr and provide custom output.

Is it advisable to use function like below:

dump(){
    "$@" > /dev/null 2>&1
}

And, then

dump rm filename || echo "custom-message"

What are the possible cases where it fails to function as expected?

This is a good technique. I use something like it all the time. Pros:

  • Preserves the exit code of the command.
  • Hides output of almost every program unless they directly write to /dev/tty or /dev/console , which is rare and probably for good reason anyways.
  • Works on shell builtins just as well as binaries. You can use this for cd , pushd / popd , etc.
  • Doesn't stop the command from reading from stdin. dump can be used at the end of a pipeline if you wish.
  • "$@" properly handles command names and arguments with whitespace, globs, and other special characters.

It looks good to me!

The only nitpick I have is that the name dump isn't the clearest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM