~/.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
fi
$ export BASH_ENV=~/.bashenv
$ bash -c 'echo bar'
foo
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.
echo foo
in the script would printfoo
, but this would not be "before execution". Please make sure there is no XY problem here. [Edit] the question if there is. Why do you needfoo
to be printed before actual execution? Before execution of any script? or before execution of this exact script only? – Kamil Maciorowski Mar 02 '24 at 14:25trap
) – Foo Mar 02 '24 at 14:39foo
only in interactive shells since you're looking fori
in$_
. And what do you mean by "before any script"? What's a script? Shell scripts only? Perl? Python? – terdon Mar 02 '24 at 14:45foo
then installation scripts are going to be confused, and may do the wrong thing. – icarus Mar 02 '24 at 19:10