I searched and didn't find, and had to figure stuff out... I hope to save you the trouble.

Monday, November 30, 2009

Determining if BASH is interactive

It's sometimes useful to know if the current BASH shell is interactive or not so that you can do things in your .bashrc only when it's interactive. When a script is run as an executable, particularly as part of a command pipeline, you might not want to do things that might mess with the environment or influence the data in the pipeline.

You can use the $- special parameter to know if the shell is interactive. Combine that with substitution in the parameter expansion and you can isolate just the 'i' that indicates it's an interactive shell. Assign the result to a environment variable that will either be the 'i' or empty, and that can be used with the [[, [, or test builtin commands that treat an empty string as false to determine whether or not to do something.

INTERACTIVE_SHELL=${-//[^i]}
if [ $INTERACTIVE_SHELL ]; then
source ~/my_interactive_stuff.sh
fi

Followers