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