Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raise exception on shell command failure?

I'm writing some scripts in Ruby, and I need to interface with some non-Ruby code via shell commands. I know there are at least 6 different ways of executing shell commands from Ruby, unfortunately, none of these seem to stop execution when a shell command fails.

Basically, I'm looking for something that does the equivalent of:

set -o errexit

...in a Bash script. Ideally, the solution would raise an exception when the command fails (i.e., by checking for a non-zero return value), maybe with stderr as a message. This wouldn't be too hard to write, but it seems like this should exist already. Is there an option that I'm just not finding?

like image 942
Benjamin Oakes Avatar asked Feb 08 '10 22:02

Benjamin Oakes


People also ask

How do I stop a shell script from failing the command?

Exit When Any Command Fails This can actually be done with a single line using the set builtin command with the -e option. Putting this at the top of a bash script will cause the script to exit if any commands return a non-zero exit code.

What is $? == 0 in shell script?

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.

What does != Mean in shell script?

And the != operator means 'is not equal to', so [ $? != 0 ] is checking to see if $? is not equal to zero. Putting all that together, the above code checks to see if the grep found a match or not.

How do you throw a bash script error?

Using the set -e Option. Bash has this built-in set command to set different options in the shell. One of the many options is errexit. Merely setting this option helps us exit the script when any of the commands return a non-zero status.


2 Answers

Ruby 2.6 adds an exception: argument:

system('ctat nonexistent.txt', exception: true) # Errno::ENOENT (No such file or directory - ctat)
like image 114
Benjamin Oakes Avatar answered Sep 22 '22 13:09

Benjamin Oakes


Easiest way would be to create a new function (or redefine an existing one) to call system() and check the error code.

Something like:

old_sys = system

def system(...)
  old_system(...)
  if $? != 0 then raise :some_exception
end

This should do what you want.

like image 24
user269044 Avatar answered Sep 21 '22 13:09

user269044