user2267134
user2267134

Reputation: 361

How to undo exec > /dev/null in bash?

I used

exec > /dev/null

to suppress output.

Is there a command to undo this? (Without restarting the script.)

Upvotes: 21

Views: 10586

Answers (5)

Berkant İpek
Berkant İpek

Reputation: 1124

Save the original output targets beforehand.

# $$ = the PID of the running script instance
STDOUT=`readlink -f /proc/$$/fd/1`
STDERR=`readlink -f /proc/$$/fd/2`

And restore them again using exec.

exec 1>$STDOUT 2>$STDERR

If you use /dev/tty for restoration as in the answers above, contrary to this, you won't be able to do redirections in call-level, e.g. bash script.sh &>/dev/null won't work.

Upvotes: 2

To restore stdout I use

unset &1

Upvotes: -1

Charles Duffy
Charles Duffy

Reputation: 295325

To do it right, you need to copy the original FD 1 somewhere else before repointing it to /dev/null. In this case, I store a backup on FD 5:

exec 5>&1 >/dev/null
...
exec 1>&5

Another option is to redirect stdout within a block rather than using exec:

{
    ...
} >/dev/null

Upvotes: 25

Vaughn Cato
Vaughn Cato

Reputation: 64308

If you just want to get output again at the command prompt, you can do this:

exec >/dev/tty

If you are creating a script, and you want to have the output of a certain group of commands redirected, put those commands in braces:

{
   command
   command
} >/dev/null

Upvotes: 5

chepner
chepner

Reputation: 530970

Not really, as that would require changing the state of a running process. Even assuming you could, whatever you wrote before resetting standard output is truly, completely gone, as it was sent to the bit bucket.

Upvotes: -1

Related Questions