bash:check_if_bash_is_running_in_interactive_mode

This is an old revision of the document!


BASH - Check if bash is running in interactive mode

if [[ $- == *i* ]]
then
  do_interactive_stuff
fi

NOTE: According to man bash:

  • PS1 is set and $- includes i if bash is interactive, allowing a shell script or a startup file to test this state.

if [ -t 0 ] ; then
  echo stdin is a terminal
  .....
fi

or

if [ -t 1 ] ; then
  echo stdout is a terminal
fi

NOTE: -t FD is True if FD is opened on a terminal.

Portable between shells.


Examples

bash <<< 'test -t 0 && echo Y || echo X

writes X

bash -c 'test -t 0 && echo Y || echo X

writes Y

NOTE: This also verifies that the standard input is a TTY; although it can be related but it is NOT the same as the shell's interactive mode, which is requested and indicated by shell's “-i” flag.


bash/check_if_bash_is_running_in_interactive_mode.1612435422.txt.gz · Last modified: 2021/02/04 10:43 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki