Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash get return value of a command and exit with this value

Tags:

bash

I want to execute a command then get the return value of this command. when it's done i want to exit and give exit the return value of the previous command, the one i just executed. I already have this piece of code but it doesn't seem to work.

exec gosu user /var/www/bin/phpunit -c app
typeset ret_code
ret_code=$?
if [ $ret_code == 0 ]; then
    exit 0
fi

exit 1

how can i do it ? thanks

like image 614
RomMer Avatar asked May 05 '17 09:05

RomMer


2 Answers

I think your problem is that typeset itself creates a return value of 0. Try

gosu user /var/www/bin/phpunit -c app
ret_code=$?
return $ret_code
like image 175
jschnasse Avatar answered Oct 14 '22 09:10

jschnasse


First of all, exec only returns if it fails, so you'll never see a zero exit status.

exec gosu user /var/www/bin/phpunit -c app
ret_code=$?
printf 'Error in execing gosu, %d\n' $ret_code
exit $ret_code

Note this error has nothing to do with gosu; if exec returns, it is because the shell was unable to even start gosu, not because gosu itself exited with an error.

Perhaps you didn't mean to use exec, and simply want to run the command and wait for it to complete?

gosu user /var/www/bin/phpunit -c app
ret_code=$?
if [ $ret_code = 0 ]; then exit 0; fi
printf 'Error in execing gosu, %d\n' $ret_code
exit $ret_code
like image 29
chepner Avatar answered Oct 14 '22 11:10

chepner