4

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?

2
  • Are you expecting the echo to be silenced by dump as well? It won't be. Commented Oct 5, 2015 at 14:12
  • @chepner: You mean that of "custom-message"? No, that should be displayed. Generally, I prefer to use some function instead of echo that take argument and do echo over those arguments and then exit. Commented Oct 5, 2015 at 14:19

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for reply. What function name would you suggest?
quiet or silent perhaps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.