1

Consider this script that calls into a function that sets up a trap for the RETURN of that function:

#!/usr/bin/env bash
set -euo pipefail

function f1() {
  local temp_file
  temp_file="$(mktemp)"
  trap 'echo DELETED; rm -- "${temp_file}"' RETURN
  date > temp_file
}

function main() {
  for i in $(seq 0 2); do
    f1
  done
}

main

For some reason this prints DELETED string 4 times (instead of 3) and fails with an unbound variable error:

DELETED
DELETED
DELETED
DELETED
hack/deploy-example-server.sh: line 13: temp_file: unbound variable

Clearly, something is causing an extra execution of this trap, I'm suspecting it's the overall script's exit.

This does not happen if I eliminate function main, and just call f1 in a for-loop in the top-level script.

What's causing this behavior?

  • I believe it's the return from main() that causes the extra execution but the whole thing looks like a specification-by-implementation bug to me. – NickD Aug 28 '19 at 22:11
  • The RETURN trap will be executed for all the callers through to the main script. Example: bash -c 'foo(){ bar; }; bar(){ baz; }; baz(){ trap "echo \${FUNCNAME[@]}" RETURN; }; foo'. I wasn't able to find this clearly mentioned anywhere. – mosvy Aug 29 '19 at 2:40
  • 1
    btw, if you copied my example in a file and run it as bash file, you would see that it's not a good idea to call a function main in bash. – mosvy Aug 29 '19 at 2:43

Your Answer

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

Browse other questions tagged or ask your own question.