Work the Shell - Understanding Exit Codes
Now that you know how to capture and analyze the exit codes from system commands, what if you want to have the error message be one from your script, not one from the command itself?
That's done with another new shorthand notation: >&, which redirects the stderr/error output stream. Here's how I use that to hide all error messages from the mkdir command being used in our sample scripts:
mkdir /usr >& /dev/null
You also can use &> or 2>&1 instead of >&.
If you don't test the results of the command, of course, you seriously can hose things up, but this makes the output more elegant for sure:
$ ./test.sh mkdir /usr failed: we have an exit code of 0
Hmmm...I'm still getting that false 0. Oh! I haven't added the code to save the exit code value as “error”. One slight tweak later and:
$ ./test.sh mkdir /usr failed: we have an exit code of 1
That's more like it!
I'm going to call this a wrap for this month. Next month, I'll demonstrate how the exit command lets you send exit codes back to the calling program from procedures and functions, just as if they were separate Linux commands rather than part of the same shell script.
Dave Taylor has been hacking shell scripts for a really long time, 30 years. He's the author of the popular Wicked Cool Shell Scripts, and he can be found on Twitter as @DaveTaylor and more generally at www.DaveTaylorOnline.com.
Dave Taylor has been hacking shell scripts for over thirty years. Really. He's the author of the popular "Wicked Cool Shell Scripts" and can be found on Twitter as @DaveTaylor and more generally at www.DaveTaylorOnline.com.
- Handling the workloads of the Future
- Readers' Choice Awards 2014
- diff -u: What's New in Kernel Development
- How Can We Get Business to Care about Freedom, Openness and Interoperability?
- Synchronize Your Life with ownCloud
- Days Between Dates?
- Non-Linux FOSS: Don't Type All Those Words!
- Computing without a Computer
- December 2014 Issue of Linux Journal: Readers' Choice
Editorial Advisory Panel
Thank you to our 2014 Editorial Advisors!
- Jeff Parent
- Brad Baillio
- Nick Baronian
- Steve Case
- Chadalavada Kalyana
- Caleb Cullen
- Keir Davis
- Michael Eager
- Nick Faltys
- Dennis Frey
- Philip Jacob
- Jay Kruizenga
- Steve Marquez
- Dave McAllister
- Craig Oda
- Mike Roberts
- Chris Stark
- Patrick Swartz
- David Lynch
- Alicia Gibb
- Thomas Quinlan
- Carson McDonald
- Kristen Shoemaker
- Charnell Luchich
- James Walker
- Victor Gregorio
- Hari Boukis
- Brian Conner
- David Lane