if tty -s; then
echo "interactive"
fi
This method does the job, but invloves process invocation (fork/exec) of tty
, which is expensive in terms of performance.
But there's a worse side-effect:
If PATH
is empty or wrong, calling tty
will fail. When sourced for a login shell,
bash
may emmit an error. Otherwise this may end the shell.
if [[ $- =~ "i" ]]; then
echo "interactive"
fi
The check here uses only bash
builtins. It's much safer and performs better.
case $- in
*i*) echo "interactive";;
esac
Similar to the above method, useful if you want to test other set
flags.