Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bash – [: =: unary operator expected during trap execution

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Could someone share a pointer please ? Thank you

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading