Skip to main content
added 363 characters in body
Source Link
glenn jackman
  • 88.5k
  • 16
  • 124
  • 179

I think you're looking for the RETURN signal:

[...] If a SIGNAL_SPEC is EXIT (0) ARG is executed on exit from the shell.
[...] If a SIGNAL_SPEC is RETURN, ARG is executed each time a shell function or a script run by the . or source builtins finishes executing.

Example:

$ bash
$ trap "echo shell exiting" EXIT
$ fn() { trap "echo function exiting" RETURN; }
$ fn
function exiting
$ (fn)
function exiting
$ value=$(fn); echo "$value"
function exiting
$ exit
shell exiting

and, germaine to the question:

$ f2() { 
    local tmp=$(mktemp)
    trap 'rm "$tmp"' RETURN
    echo "$tmp"
    date >> "$tmp"
    cat "$tmp"
}
$ f2
/tmp/tmp.MHpI20X0a1
Fri May 11 14:29:01 EDT 2018
$ ls -l /tmp/tmp.MHpI20X0a1
ls: cannot access '/tmp/tmp.MHpI20X0a1': No such file or directory

I think you're looking for the RETURN signal:

[...] If a SIGNAL_SPEC is EXIT (0) ARG is executed on exit from the shell.
[...] If a SIGNAL_SPEC is RETURN, ARG is executed each time a shell function or a script run by the . or source builtins finishes executing.

Example:

$ bash
$ trap "echo shell exiting" EXIT
$ fn() { trap "echo function exiting" RETURN; }
$ fn
function exiting
$ (fn)
function exiting
$ value=$(fn); echo "$value"
function exiting
$ exit
shell exiting

I think you're looking for the RETURN signal:

[...] If a SIGNAL_SPEC is EXIT (0) ARG is executed on exit from the shell.
[...] If a SIGNAL_SPEC is RETURN, ARG is executed each time a shell function or a script run by the . or source builtins finishes executing.

Example:

$ bash
$ trap "echo shell exiting" EXIT
$ fn() { trap "echo function exiting" RETURN; }
$ fn
function exiting
$ (fn)
function exiting
$ value=$(fn); echo "$value"
function exiting
$ exit
shell exiting

and, germaine to the question:

$ f2() { 
    local tmp=$(mktemp)
    trap 'rm "$tmp"' RETURN
    echo "$tmp"
    date >> "$tmp"
    cat "$tmp"
}
$ f2
/tmp/tmp.MHpI20X0a1
Fri May 11 14:29:01 EDT 2018
$ ls -l /tmp/tmp.MHpI20X0a1
ls: cannot access '/tmp/tmp.MHpI20X0a1': No such file or directory
Source Link
glenn jackman
  • 88.5k
  • 16
  • 124
  • 179

I think you're looking for the RETURN signal:

[...] If a SIGNAL_SPEC is EXIT (0) ARG is executed on exit from the shell.
[...] If a SIGNAL_SPEC is RETURN, ARG is executed each time a shell function or a script run by the . or source builtins finishes executing.

Example:

$ bash
$ trap "echo shell exiting" EXIT
$ fn() { trap "echo function exiting" RETURN; }
$ fn
function exiting
$ (fn)
function exiting
$ value=$(fn); echo "$value"
function exiting
$ exit
shell exiting