I am trying to use trap in order to run a clean-app jar in case the main app jar exists successfully (0 exit code) :
trap "exit_code=$?; if [ "${exit_code}" = "0" ]; then java -jar /clean-app.jar; fi" EXIT
java -jar /main-app.jar
but I am getting the following error and not sure I'm getting the reason behind it :
/bin/bash: line 1: [: =: unary operator expected
Could someone share a pointer please ? Thank you
CodePudding user response:
You can't nest double quotes like this. Here, you can switch to single quotes for the outer layer. You'll want to do this anyway because you need to prevent $?
from being expanded before trap
is called.
trap 'exit_code=$?; if [ "${exit_code}" = "0" ]; then java -jar /clean-app.jar; fi' EXIT
Better yet, define a function first.
handler () {
exit_code=$?
if [ "$exit_code" = 0 ]; then java -jar /clean-app.jar; fi
}
trap handler EXIT
In either case, you don't really need exit_code
, as you don't need the original exit code after the test. You can also use -eq
, since $?
is guaranteed to be an integer.
handler () {
[ $? -eq 0 ] && java -jar /clean-app.jar
}