I have a bash script that executes a bunch of ruby scripts.
#!/bin/bash
ruby script_1.rb
ruby script_2.rb
ruby script_3.rb
If any of the ruby scripts fail it exists using exit
with code 1
. In the case of an exit how can I also exit the bash script midway?
I understand that bash can exit using exit N
but how can it catch exit from ruby? Should the ruby script throw an execption for this to work?
CodePudding user response:
Don't do anything fancy. (set -e
is fancy, or perhaps pathological. Many will suggest using it. Ignore them)
Just do something like:
#!/bin/bash
ruby script_1.rb &&
ruby script_2.rb &&
ruby script_3.rb
or
#!/bin/bash
ruby script_1.rb || exit 1
ruby script_2.rb || exit 1
ruby script_3.rb || exit 1
You may be tempted to add additional error messages. Avoid that temptation. If you need an error message, it should be written by the ruby script, since it has details about what the error is.
CodePudding user response:
You can check the exit code with $?
:
#!/bin/bash
ruby script_1.rb
if [[ $? == 1 ]]; then
exit 1
fi
#...
You can use a helper function to do the same check over and over again:
#!/bin/bash
function exit_if_code {
if [[ $? == $1 ]]; then
exit $1
fi
}
ruby script_1.rb
exit_if_code 1
ruby script_2.rb
exit_if_code 1
ruby script_3.rb
exit_if_code 1