Skip to content

Instantly share code, notes, and snippets.

@otzoran
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save otzoran/6a5e96d0adc9f5c7721c to your computer and use it in GitHub Desktop.
Save otzoran/6a5e96d0adc9f5c7721c to your computer and use it in GitHub Desktop.
Check if bash shell is interactive

The old way

if tty -s; then
  echo "interactive"
fi

Cons

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.

The better way

if [[ $- =~ "i" ]]; then
  echo "interactive"
fi

Pros

The check here uses only bash builtins. It's much safer and performs better.

The better way [2]

case $- in
   *i*) echo "interactive";;
esac

Pros

Similar to the above method, useful if you want to test other set flags.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment