We will use ‘tty’ which normally prints the file name of the connected terminal on standard input.
To make our life easier we will add the parameter -s (silent), ‘tty -s’ will print nothing and return an exit status.
tty has the following possible values for exit status:
- 0: if standard input is a terminal
- 1: if standard input is not a terminal
- 2: if given incorrect arguments
- 3: if a write error occurs
So in order to check if this script is attached to a terminal we have to do something similar to this:
if [ "0" == "$?" ]; then
echo "Terminal attached, you can print data as there might be a user viewing it.";
echo "No terminal attached, there might not be a reason to print everything.";
Note: In the above script we use ‘$?’, that variable contains the return value of the last executed command, so If you are planning on using it like this, make sure you do not place any other command in between the tty -s and the if statement.