17

My Bash script calls a lot of commands, most of them output something. I want to silence them all. Right now, I'm adding &>/dev/null at the end of most command invocations, like this:

some_command &>/dev/null
another_command &>/dev/null
command3 &>/dev/null

Some of the commands have flags like --quiet or similar, still, I'd need to work it out for all of them and I'd just rather silence all of them by default and only allow output explicitly, e.g., via echo.

2

2 Answers 2

17

You can use the exec command to redirect everything for the rest of the script.

You can use 3>&1 to save the old stdout stream on FD 3, so you can redirect output to that if you want to see the output.

exec 3>&1 &>/dev/null
some_command
another_command
command_you_want_to_see >&3
command3
Sign up to request clarification or add additional context in comments.

Comments

0

You can create a function:

run_cmd_silent () {
    # echo "Running: ${1}"
    ${1} > /dev/null 2>&1
}

You can remove the commented line to print the actual command you run.

Now you can run your commands like this, e.g.:

run_cmd_silent "git clone [email protected]:prestodb/presto.git"

2 Comments

This introduces all kinds of problems with whitespace and parameter handling.
"$@" is designed for this: run_cmd_silent() { "$@" > /dev/null 2>&1; }; run_cmd_silent git clone [email protected]:prestodb/presto.git

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.