0

I have a bash function which is invoked as a child process (though backticks) from by bash script. Is there any way to have this function (running in the child process) modify the parent's trap handlers? This function creates a temporary file which I would like to be cleaned up when the parent exits. As an example

function get_roe_dir() {
    tmp_dir=`mktemp -d`
    if [ $? -eq 0 ]; then
        # some processing on $tmp_dir
        echo "$tmp_dir"
        # Add "rm -rf $tmp_dir" to parent's EXIT trap
    fi
}

Then, in the calling script, I have something like:

roe_dir=`get_roe_dir`
# Some processing using files in $roe_dir.

Once this script exits, I'd like $roe_dir to get deleted (using the EXIT trap). Any ideas for clean ways to achieve this?

I cannot add an EXIT trap to the get_roe_dir() function because it is executed in a sub-shell to capture the output. Therefore, as soon as get_roe_dir() has returned, the subshell exits and the EXIT trap is called, deleting the temporary directory it created.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Taj Morton
  • 1,588
  • 4
  • 18
  • 26
  • 2
    No, there's no way to modify anything in the parent's environment. – Barmar Jul 25 '13 at 19:59
  • Not really understand what you want. Why you didn't set the trap handler in the `get_roe_dir`? Post more precise question (fragment of both scripts - parent/child). – clt60 Jul 25 '13 at 20:51

1 Answers1

0

Maybe don't understand corectly, but the next works:

set_trap() {
    trap "rm -rf $roe_dir" 0
}

get_roe_dir() {
    dir=$(mktemp -d /tmp/roe.XXXXXX) && echo $dir && return 0
    return 1
}

roe_dir=$(get_roe_dir) && set_trap
ls -la "$roe_dir"
echo going to exit - check ls -l $roe_dir should not exists
clt60
  • 62,119
  • 17
  • 107
  • 194
  • I will try to clarify the question above, but I was wanting `get_roe_dir` to set the trap. Your example works, but it relies on the caller of the function to also call `set_trap()`, which is what I was hoping to avoid. Thanks! – Taj Morton Jul 25 '13 at 21:48
  • 1
    What you want is impossible. The child CANT modify the parent. – clt60 Jul 25 '13 at 21:52