Work the Shell - Handling Errors and Making Scripts Bulletproof
Finally, another thing to be aware of with the shell is that it's all too easy to zap important files with a redirect. For example, this shouldn't work:
$ who > who.output $ ls > who.output
The second command should generate an error because the output file already exists, right? But it doesn't, and it simply trashes the who output without a warning or error—not good.
To avoid that problem, you'll want to set -o noclobber in scripts or, better, for your login shell, and let it be inherited by subshells, including those that run your shell scripts. A good place to put it could be in your .profile or .bashrc.
With noclobber set, the two commands behave differently:
$ ls > who.output -bash: who.output: cannot overwrite existing file
That's useful for everyone, and doubly so for us shell script hackers, right?
Dave Taylor is a 26-year veteran of UNIX, creator of The Elm Mail System, and most recently author of both the best-selling Wicked Cool Shell Scripts and Teach Yourself Unix in 24 Hours, among his 16 technical books. His main Web site is at www.intuitive.com, and he also offers up tech support at AskDaveTaylor.com. Follow him on Twitter if you'd like: twitter.com/DaveTaylor.
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.
Webinar: 8 Signs You’re Beyond Cron
On Demand NOW
Join Linux Journal and Pat Cameron, Director of Automation Technology at HelpSystems, as they discuss the eight primary advantages of moving beyond cron job scheduling. In this webinar, you’ll learn about integrating cron with an enterprise scheduler.View Now!
|Non-Linux FOSS: Vienna, Not Just for Sausages||Jun 02, 2015|
|June 2015 Issue of Linux Journal: Networking||Jun 01, 2015|
|June 2015 Video Preview||Jun 01, 2015|
|My Humble Little Game Collection||May 28, 2015|
|New Linux Based OS Brings Internet of Things Closer to Reality||May 27, 2015|
|Non-Linux FOSS: All the Bitcoin, None of the Bloat||May 26, 2015|
- June 2015 Issue of Linux Journal: Networking
- Non-Linux FOSS: Vienna, Not Just for Sausages
- New Linux Based OS Brings Internet of Things Closer to Reality
- Dr Hjkl on the Command Line
- Download "Linux in the Time of Malware"
- Initializing and Managing Services in Linux: Past, Present and Future
- Using Hiera with Puppet
- My Humble Little Game Collection
- Gartner Dubs DivvyCloud Cool Cloud Management Vendor
- Infinite BusyBox with systemd