0

I'm trying to let a command run in the background, but also use the "||" syntax to execute a different command if the first one failed. Example:

$( <run-this-in-background> & || <run-this-if-failed>)

However I'm getting a syntax error:

command substitution: line 15: syntax error near unexpected token `||'

This is the exact line:

$(./temptwo.sh & || rc=$?)

My full code is as follows... I know it seems a bit weird to do rc=$? when I could just do that in the following line, however we are using a logger that will exit your program if any line exits with $? != 0, so the way we get around it is by using "./someCommand || rc=$?" which will exit with "0", but also give us the return code.

#default success code: 
rc=0 
#run temptwo.sh in the background. If it fails, set rc=$?
$(./temptwo.sh & || rc=$? )
#Trying to get the process id of "temptwo.sh" below (not sure if works)
pid=$! 
#Wait until the process finishes
wait $pid 
  • 1
    Unless you wait until it has finished, how will you know that it has failed? – NickD Mar 20 '18 at 21:47
  • When I do "$?" after the "wait" command, it gets the exit code. The "rc" never has the right exit code though, so I just throw that one away lol – Katie Mar 23 '18 at 16:25
1
/temptwo.sh & pid=$! ; wait $pid || rc=$?

Doesn't make much sense IMHO, though.

/temptwo.sh & pid=$! ; wait $pid ; rc=$?
if [ "$rc" -gt 0 ]; then
...
  • That worked! Thank you! Yeah it definitely feels odd.. thank you for answering my question even though the idea is weird ^-^ – Katie Mar 20 '18 at 22:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.