[Tfug] Problem checking return code in bash script

Choprboy choprboy at dakotacom.net
Tue Oct 6 01:57:27 MST 2009


On Monday 05 October 2009 21:23, Chad Woolley wrote:
> I'm writing a script which automates system setup, with logic like this:
>
> sudo su -l -c "ruby ~/railsci/setup_rails_dependencies.rb" ci
> if [ ! $? = 0 ]; then echo "Unable to setup rails dependencies" && exit; fi
>
> However, even if the command returns a non-zero return code (tested by
> running manually), the script keeps going and doesn't exit.
>

Your program is testing the exit status of the command you gave, i.e. 
the "sudo". The sudo suceeded... it was the sudo'd command that failed. The 
sudo creates a subshell, and the su also creates a subshell, so your are 
really 3 subshells down when executing ruby. The upper shell completed 
successfully.

Bury your "if" down in your su command, re-write it as an OR 
(i.e. "ruby ./xxx || echo "failed" " ), or write your ruby into a shell 
script that contains the error handling code and then just sudo the script.


Adrian





More information about the tfug mailing list