With options, I want to change what happens when a script exits or crashes, for instance, don't clean up the logs and temporary files if it's not a clean exit.

I know I can invoke a function in trap's actions. However, since those usually need processing before getting to the program/instructions section of the script. I would need to use variables that get evaluated much later.

From what I understand things like functions are loaded into memory and don't get read again until the script itself is read again.

Would it work — and, if not — is there a way to do it? Thanks.

  • Function in bash are not evaluated when the script loads, but only when actually being called. By default, unless explicitly stated, all variables are global, which means that any time your function runs (even if triggered by a trap), it sees the current value of each variable.
    – aviro
    Feb 23, 2023 at 8:19
  • 2
    By the way, I don't understand how stdin that appears in the tital of the question is related to the actual question.
    – aviro
    Feb 23, 2023 at 8:23
  • I had forgotten that part about functions. I know this is super easy to you so thanks for bearing with me anyway. I solved it with a function that has an if statement like "if [ ${performCleanup:-$performCleanupPreset} = no ]". A while+case loop sets changes the variable. I wish you had written this as an answer though.
    – Vita
    Feb 25, 2023 at 3:48

1 Answer 1


If I understand your question correctly, you want to "inject" behavior in an otherwise unmodified shell script.

Check the bash man page, look for BASH_ENV. The referenced file will be executed before the actual script. Depending on what that existing script does at runtime, you might be able to tweak its behavior that way.

This example creates a BASH_ENV script and the actual script. As you can see, the trap set by the code in BASH_ENV gets executed.

set -ex
read td < <(mktemp --directory --tmpdir=/dev/shm .XXX)
trap "rm -rf ${td}" EXIT
cat > ${t_BASH_ENV} <<'_EOF_'
trap ": trapped t_BASH_ENV $PPID $$" EXIT
cat > ${t_BASH_SCRIPT} <<'_EOF_'
env -i BASH_ENV=${t_BASH_ENV} bash -x "${t_BASH_SCRIPT}"


+ read td
++ mktemp --directory --tmpdir=/dev/shm .XXX
+ trap 'rm -rf /dev/shm/.vJp' EXIT
+ t_BASH_ENV=/dev/shm/.vJp/BASH_ENV
+ cat
+ cat
+ env -i BASH_ENV=/dev/shm/.vJp/BASH_ENV bash -x /dev/shm/.vJp/BASH_SCRIPT
+ : t_BASH_ENV 4438 4443
+ trap ': trapped t_BASH_ENV 4438 4443' EXIT
+ : t_BASH_SCRIPT 4438 4443
+ : trapped t_BASH_ENV 4438 4443
+ rm -rf /dev/shm/.vJp


  • Thanks, I had forgotten functions had different rules. I've been reading the man page, well… gnu.org/software/bash/manual/bash.html . But, for newbies, at times it can be quite dense. Thanks for answering nevertheless, I truly appreciate it.
    – Vita
    Feb 25, 2023 at 3:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .