How can I ensure that I always run something when a non-interactive shell is launched?

Let’s say I have a script:


I would like to have it so that when I execute this script, foo is always printed before its execution. In fact, I would want foo to be printed before execution of any script (not just this example).

I tried playing around with the bashrc file however this doesn’t seem to work:

case $- in
    *i*) echo "foo";;
      *) return;;
Asked By: Foo


~/.bashrc is only interpreted by non-login interactive invocations of bash not running in posix mode┬╣

For a file that is interpreted by every invocation of bash (excluding ones running in posix mode), you can use $BASH_ENV:

$ cat ~/.bashenv
if [[ $- != *i* ]]; then
  echo foo
$ export BASH_ENV=~/.bashenv
$ bash -c 'echo bar'

If that echo foo is only meant to be interpreted by bash scripts, that is when bash is invoked as bash /path/to/file (like with a #! /bin/bash shebang or the more correct #! /bin/bash - form) and not other forms of non-interactive shell invocations (like bash -c code (as done by xterm, vi, GNU parallel… when running $SHELL code), or bash < file) you can change the [[ $- != *i* ]] to [[ $- != *[ics]* ]].

The equivalent for zsh is ~/.zshenv (or $ZDOTDIR/.zshenv).

All csh/tcsh invocations read ~/.cshrc (~/.tcshrc) unless passed -f (which is why most csh scripts have a #! /bin/csh -f shebang).

ksh used to honour $ENV but that was stopped for non-interactive shells for security reasons ($ENV processing for interactive invocations is still a POSIX requirement for sh and the only way to have a shell customisation file there).

┬╣ Like when invoked as sh or when there’s $POSIXLY_CORRECT or SHELLOPTS=posix in the environment or if called wih -o posix. ~/.bashrc may also be interpreted by bash shells when invoked even non-interactively over ssh with some builds of bash. bash startup file processing is a bit of a mess.

Answered By: Stéphane Chazelas
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.