Borek Bernard
Borek Bernard

Reputation: 53231

How to silence output of all commands in a Bash script?

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.

Upvotes: 17

Views: 4277

Answers (2)

Chananel P
Chananel P

Reputation: 1814

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"

Upvotes: 0

Barmar
Barmar

Reputation: 780798

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

Upvotes: 17

Related Questions