How to test if a shell is interactive

If you want your script to behave differently if it is run from say a cron job for example or by a user then you can perform the following test.

In bash:

if [ -z "$PS1" ]; then
   echo This shell is not interactive
else
   echo This shell is interactive
fi

In perl:

if($ENV{'PS1'}){
   print "This shell is interactive\\n";
}
else{
   print "This shell is not interactive\\n";
}

Last updated: 28/10/2006