I know of two ways to test whether a shell is interactive,

[[ $- == *i* ]] && echo "-i option flag indicates interactive"

[ -n "$PS1" ] && echo "prompt is set"

I've read that checking for the i option flag is more reliable, which makes sense given that it's an explicit indicator of interactivity.

But when I look through the startup files on my system (e.g. /etc/profile, /etc/bash.bashrc), they check PS1. I'm running Ubuntu. I don't know how platform-specific this is.

I'm wondering whether this means:

  • the authors of the startup files are not as skilled as I assumed
  • PS1 is reliable enough in this context
  • PS1 is reliable enough in general, and I'm overthinking things

On my Ubuntu 16.04 system, this is the check in /etc/profile:

if [ "$PS1" ]; then
  if [ "$BASH" ] && [ "$BASH" != "/bin/sh" ]; then
    # The file bash.bashrc already sets the default PS1.
    # PS1='\h:\w\$ '
    if [ -f /etc/bash.bashrc ]; then
      . /etc/bash.bashrc
    if [ "`id -u`" -eq 0 ]; then
      PS1='# '
      PS1='$ '

... which seems to me is mostly concerned about setting PS1 (and not for controlling the behaviour of the rest of the rc file). I don't see how testing for -i would help in that.

  • That's a good point. Have a look at /etc/bash.bashrc though. – ivan Oct 18 '17 at 12:32
  • @ivan hmmm. In that case, I'd note that checking PS1 for bash should be equivalent - since bash unsets PS1 if not interactive (compare PS1=foo bash --noprofile --norc -c 'echo $PS1' vs PS1=foo bash --noprofile --norc -ic 'echo $PS1'). Also: bash documentation treats both as equally valid. – muru Oct 18 '17 at 12:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.