Skip to main content

How to Stop a Ruby Script with an Error Message Using abort

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

When a script can't go on, it should say why and end with a failure code, so a shell, another script or a CI job knows something went wrong. Ruby's abort 'message' does both in one call.

Syntax​

Syntax
abort '<message>'
exit <code>
PartWhat it does
abort '<message>'Writes the message to standard error and ends the script with exit code 1.
exit <code>Ends the script with any exit code you choose, without a message.

The Ruby documentation for Kernel#abort: "Terminates execution immediately, effectively by calling Kernel.exit(false). If string argument msg is given, it is written to STDERR prior to termination".

The Example​

The example checks whether all orders are paid. They aren't, so it aborts with a message.

Prerequisites​

  • Ruby. This guide uses Ruby 4.0.10.

Step 1: Write the Code​

Create a file named main.rb:

main.rb, which sets all_paid to false, aborts with Some orders are not paid. if not all_paid, and otherwise puts All orders are paid.

main.rb
all_paid = false

abort 'Some orders are not paid.' if !all_paid

puts 'All orders are paid.'

Step 2: Run It and Read the Exit Code​

Run the script, then ask the shell for the exit code of the last command:

Terminal
ruby main.rb
echo $?

A zsh terminal where ruby main.rb prints Some orders are not paid. and echo $? prints 1.

Output
Some orders are not paid.
1

The last line never ran. The message went to standard error: with standard error hidden, the same run printed nothing at all. The exit code was 1.

Other Exit Codes​

abort always ends with 1. For another code, print the message yourself and call exit: exit 2 ended a script with code 2.

Common Mistakes​

MistakeWhat happensDo this instead
Printing an error with puts and carrying onThe script ends with 0, so a CI job continuesUse abort
Calling abort deep inside a libraryThe whole program stops, and callers can't reactRaise an exception there and abort at the top
Expecting abort to use code 2 or moreIt's always 1Use exit with the code you need

Troubleshooting​

SymptomLikely causeFix
echo $? prints 0 after an error messageThe message was printed, but the script ended normallyUse abort or exit 1
The message is missing from a log fileIt went to standard error, and only standard output was savedAdd 2> errors.txt

FAQ​

What does abort without a message do?​

It still ends the script with code 1, silently.

Does abort run at_exit blocks?​

Yes. It ends the script the way exit(false) does, so at_exit handlers still run.

Conclusion​

abort 'message' writes the reason to standard error and ends the script with code 1, which the shell reads as $? in zsh or bash and $LASTEXITCODE in PowerShell. Use exit when you need another code.

Additional Resources​