What's the preferred way to determine if a given ksh invocation is running an interactive shell?
I have some commands in an ENV
file that I would like to skip for non-interactive ksh invocations (e.g. when executing a shell script).
I've seen suggesting ranging from:
if [[ $- = *i* ]]; then
# do interactive stuff
fi
...to not even sourcing .kshrc
unless the shell is determined to be interactive using this cryptic incantation:
ENVIRON=$HOME/.kshrc export ENVIRON
ENV='${ENVIRON[(_$-=1)+(_=0)-(_$-!=_${-%%*i*})]}' export ENV
If a script needs to test whether it is running in an interactive shell, it is simply a matter of finding whether the prompt variable, $PS1 is set. (If the user is being prompted for input, then the script needs to display a prompt.) Alternatively, the script can test for the presence of option "i" in the $- flag.
An interactive shell is defined as the shell that simply takes commands as input on tty from the user and acknowledges the output to the user. This shell also reads startup files that occurred during activation and displays a prompt.
I have found checking the $- variable for the 'i' flag the best method in ksh.
if [[ $- = *i* ]]; then
#do interactive stuff
fi
In bash, these two methods are often used inside ~/.bashrc
:
Check if stdin
is a tty:
[ -t 0 ] || return
or
if [ -t 0 ]; then
# do interactive stuff
fi
Check if the prompt ($PS1
) is set:
[ -z "$PS1" ] || return
But I don't know how to do that in ksh.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With