inside of my script I need to run two scripts as another user, so I used the following line:
su otherUser -c "firstScript;secondScript;status=$?"
echo "returning $status"
return $status
The problem is that $status will always return 0.I did test with secondScript failing (wrong argument). Not sure if it's because I exited otherUser or if the $status is actually the result of the su command. Any suggestions?!
You need to capture status
inside your outer shell, not in the inner shell invoked by su
; otherwise, the captured value is thrown away as soon as that inner shell exits.
This is made much easier because su
passes through the exit status of the command it runs -- if that command exits with a nonzero status, so will su
.
su otherUser -c 'firstScript; secondScript'; status=$?
echo "returning $status"
return $status
Note that this only returns the exit status of secondScript
(as would your original code have done, were it working correctly). You might think about what you want to do if firstScript
fails.
Now, it's a little more interesting if you only want to return the exit code of firstScript
; in that case, you need to capture the exit status in both shells:
su otherUser -c 'firstScript; status=$?; secondScript; exit $status'); status=$?
echo "returning $status"
return $status
If you want to run secondScript
only if firstScript
succeeds, and return a nonzero value if either of them fails, it becomes easy again:
su otherUser -c 'firstScript && secondScript'); status=$?
echo "returning $status"
return $status