1

I have an executable script hello containing the following code,

#!/bin/bash
echo "hello" > /dev/tty

I want to redirect it's output to /dev/null.

./hello > /dev/null 2>&1

doesn't work, because it redirects only stdout and stderr.

I found two answers, claiming that this can be done using script command, but they doesn't explain how.

https://unix.stackexchange.com/a/297237/421466

https://unix.stackexchange.com/a/296108/421466

Or is there any other way to suppress its output?

1 Answers1

3

changing the script

Assuming file descriptor 3 is not used yet:

#!/bin/bash
exec 3>/dev/tty
#exec 3>/dev/null
echo "hello" >&3

You open fd 3 to /dev/tty or /dev/null, easy to switch. Then you replace all > /dev/tty with >&3.

not changing the script

A solution outside the script would be to create a mount namespace (man unshare), execute mount --bind /dev/null /dev/tty in it and then run the unmodified script there.

Hauke Laging
  • 90,279
  • +1 Great answer. I wasn't aware of the consequence of not using a mount namespace and I ran the mount command directly. Doing so rendered sudo command useless and I couldn't umount /dev/tty because it required sudo privilage. Thankfully I was experimenting on a virtual machine :). – Akash Karnatak Jul 07 '20 at 14:36