ow 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.
The syntax is as follows:
// Is this Shell Interactive?
[ -z "$PS1" ] && echo "Noop" || echo "Yes"
Here is another shortcut for us:
[ -z "$PS1" ] && echo "This shell is not interactive" || echo "This shell is interactive"
## do some stuff or die ##
[ -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(1) 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:
So we can use the case…in…esac (bash case statement)
case "$-" in
*i*) echo This shell is interactive ;;
*) echo This shell is not interactive ;;
esac
OR we can use the if command:
if [[ $- == *i* ]]
then
echo "I will do interactive stuff here."
else
echo "I will do non-interactive stuff here or simply exit with an error."
fi
#ps1 #shell interactive #bash #syntax