InsertNameHere
InsertNameHere

Reputation: 21

Using Ruby to call a shell script exit code always returns as 0

I am using Ruby to call a shell script via:

%x[ /root/script.sh -k -m -l -w -p]
exitCode = %x[echo $?]

if exitCode != 0
  do something
else
  do something else
end

My problem is the exit code is always equal to 0 even when I force the script to fail. How do I properly get the exit code of the script?

EDIT: Ok came in this morning and started digging through the script as I could not get an error code of anything besides 0. The script looks something like this...

failed() {
      if [ "$1" -ne 0 ] ; then
          echo "$2 failed. INSTALLATION FAILED! Exiting.";
      exit 1;
    fi
}

{

function 1
function 2..
function ..20

} | tee -a logFile.log 

So the last thing that the script runs is always this log file meaning I never get the real exit code.

Upvotes: 0

Views: 1563

Answers (1)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

Echo is True; Inspect Your Last Process Instead

What's Wrong

Your current code will almost always evaluate its if-statement as true because /bin/echo or the shell builtin echo return success unless standard output is closed or some other error occurs. Consider the following Bash snippet:

echo `false`; echo $? # 0
echo >&-; echo $?     # 1

In addition, in your current code, exitCode is a String, not an Integer. It's being assigned the standard output of your echo command, so you'd have to call Kernel#Integer or String#to_i on it to cast the variable before attempting a valid comparison. For example, consider the following Ruby:

`echo $?`.class #=> String
"0" == 0        #=> false
"0".to_i == 0   #=> true

How to Fix the General Case

You need to test the exit status directly, or inspect the captured output. For example, in Ruby, you can test the last status of the /bin/false command with:

captured_output = `/bin/false`
$?.exitstatus
#=> 1

Fixing Your Specific Example

If you didn't understand anything above, just fix your code by stripping out all the non-essentials. Based on your example, you don't need the interim variable, nor do you actually need to store standard output. Unless you're evaluating specific non-zero exit statuses, you don't even need to inspect the process status directly or even use an equality statement.

Follow the KISS principle, and just evaluate the truthiness of the Kernel#system call. For example:

# Just call system if you don't care about the output.
# The result will be true, false, or nil.
if system('/root/script.sh -k -m -l -w -p')
  'clean exit'
else
  "non-zero exit: #{$?}"
end

Upvotes: 2

Related Questions