Site icon

Bash script: How to check if it run by a user in terminal or not


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:

So in order to check if this script is attached to a terminal we have to do something similar to this:
tty -s;
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.

This post is also available in: Αγγλικα

Exit mobile version