Bash signal capture that does not detect variables changed after the declaration of the "trap" block

I have a bunch of general cleanup code that should be executed whenever any bash script ends, regardless of whether it exited normally or was interrupted. I decided that for this I used the pseudo signal trap "..." EXIT .

In addition to the usual cleanup tools, there is also one part of a specific cleanup that should only be performed if the script completes normally. I thought I could call this if the "trap" block checks the variable, for example:

 #!/bin/bash done=false; trap "{ #generic cleanup code goes here. if $done then #cleanup to be done only on completion goes here. echo Test; fi }" EXIT #main script goes here done=true; 

However, this does not work. Executing the following code will never repeat the "Test". Adding an explicit call to exit after done=true; nothing changes. What am I missing?

Hurrah!

+6
source share
1 answer

The trap is interpolated and uses the value $ done during the definition of the trap, and not when it is executed. You can use single quotes around the definition of a trap or define a function. Function definition is probably cleaner:

  #! / bin / sh
 done = false
 cleanup () {if $ done;  then echo Test;  fi  }
 trap cleanup EXIT
 done = true

This works because the expansion of variables in a function is delayed until the function is called, and not when the function is defined.

+13
source

Source: https://habr.com/ru/post/908156/


All Articles