Bash Check If Shell Is Interactive or Not Under Linux / Unix Oses

by on November 5, 2012 · 5 comments· LAST UPDATED November 5, 2012

in

How do I check in GNU/Bash if a shell is running in interactive mode or not while writing shell scripts?

A bash shell is considered as an interactive shell when it reads and writes data from a user's terminal. Most startup scripts examine the shell variable called PS1. Usually, PS1 is set in interactive shells, and it is unset in non-interactive shells.
Tutorial details
DifficultyEasy (rss)
Root privilegesNo
RequirementsGNU/Bash
Estimated completion timeN/A

Find out if this shell interactive using PS1

The syntax is as follows:

// Is this Shell Interactive?
[ -z "$PS1" ] && echo "Noop" || echo "Yes"

OR


[ -z "$PS1" ] && echo "This shell is not interactive" || echo "This shell is interactive"

OR


[ -z "$PS1" ] && die "This script is not designed to run from $SHELL" 1 || do_interacive_shell_stuff

You can use bash shell if..else..fi syntax as follows:

 
if [ -z "$PS1" ]; then
       die "This script is not designed to run from $SHELL" 1
else
       //call our function
       do_interacive_shell_stuff
fi
 

From the bash reference manual

To determine within a startup script whether or not Bash is running interactively, test the value of the '-' special parameter. It contains i when the shell is interactive. For example:

 
case "$-" in
    *i*) echo "This shell is interactive" ;;
      *) echo "This shell is not interactive" ;;
esac
 

tty command

You can also use tty command as follows:

 
tty -s && echo "This shell is interactive" || echo "This shell is not interactive" ;;
 

OR

 
ssh user@server1.cyberciti.biz tty -s && echo "This shell is interactive" || echo "This shell is not interactive" ;;
 
References:
TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 5 comments… read them below or add one }

1 Shantanu Gadgil November 6, 2012 at 8:40 am

Whatever happened to the standard method of checking the fd ‘0’ ???

if [ -t 0 ]; then
# do stuff
fi

Don’t you think that’s a better check that some env variable?

Reply

2 jonus June 25, 2013 at 1:00 pm

that will miss the action on a fresh login.

Reply

3 Jalal Hajigholamali November 27, 2012 at 6:53 am

Hi,

Very useful article
Thanks a lot..

Reply

4 Mike February 12, 2013 at 4:36 pm

Full of holes and not reliable at all. PS1 can be defined by someone in their own .bashrc file for instance.
You’d have to stat what /dev/fd/0 points to, and sift out the text that is different.

Reply

5 felipe1982 November 27, 2013 at 12:09 am

@ Mike – what other solution do you propose, if -t 0 isn’t enought, nor is [ -z “$PS1″ ]

Reply

Leave a Comment

Tagged as: , , , , , ,

Previous Faq:

Next Faq: