Work the Shell - Function Return Codes and Daylight Calculations
Last month, I explored exit codes and how decent error correction in your shell scripts always should include testing the value of $? after each meaningful command. Writing bulletproof shell scripts also involves generous use of the test command too, a typical sequence being something like this:
if [ ! -d $DIRECTORY ] ; then echo "Error: Directory $DIRECTORY doesn't exist." exit 1 fi date > $DIRECTORY/$file if [ $? -ne 0 ] ; then echo "Error: failed with error $? trying to create $file" exit 1 fi
That reminds me, I talk about the test command, but you don't see me actually using it above. Actually, you do. It turns out, for reasons of coding clarity, there's a file called [ in your filesystem that's a link (a hard link) to the test command:
$ ls -l /bin/{[,test}
-r-xr-xr-x 2 root wheel 63184 May 18 2009 /bin/[
-r-xr-xr-x 2 root wheel 63184 May 18 2009 /bin/test
Old-school script authors use if test <condition>, and you'll sometimes see that show up, but it's rare nowadays.
This month, I want to finish this discussion by exploring how the return command within your shell scripts allows you to send information back from functions within the script itself.
Let's say you're busy programming some sort of game and find that you want to be able to ascertain whether it's daytime or nighttime when the program runs. Perhaps you have a graphical background that changes, just as Gmail has some themes that change based on your local weather.
“Aha!” I can already hear you saying, “figuring out daytime is trickier than you think, Dave!” You're right, of course, but I'll get to that in phase two. In the first phase of this function, let's create a stub that dumbly assumes that 8:00am–6:00pm is daytime, and the rest of the day is nighttime.
This can be implemented easily enough:
hour=$(date +%H) if [ $hour -ge 8 -a $hour -le 18 ] ; then yes, it's daytime else no, it's nighttime fi
That's fine, but how do you communicate that with the rest of your script without having the entire script live within some big, ugly, if-then-else statement? More important, what about when you want to make the test far more sophisticated, where it's getting sunrise/sunset times from the Internet for the current date and location?
Let's write a function that returns true if it's daytime and false otherwise. Something like this:
function isdaytime
{
hour=$(date +%H)
if [ $hour -ge 8 -a $hour -le 18 ] ; then
return 1
else
return 0
fi
}
You can reference this in your script within an if statement, as follows:
if isdaytime ; then
One of the glitches with this is that you need to use the counter-intuitive return code of 1 for failure and 0 for success. This is similar to using the exit command: you exit with 0 for success and anything else for failure. Another glitch you may recall from last month is that if you are going to be testing the return code, you easily can get messed up if there are any other commands between the invocation and the test—including a friendly debugging echo statement—because the $? will be the exit code of the most recently invoked function or program.
Assuming you want to save the return code for later use, you could invoke the function like this:
isdaytime ; daytime=$?
At this point you may think, “Wait, why not do it like this?”
function isdaytime
{
hour=$(date +%H)
if [ $hour -ge 8 -a $hour -le 18 ] ; then
daytime=1
else
daytime=0
fi
}
Any serious programmer will know the answer. It's bad form to have subroutines or functions set or alter global variables. Why? Because debugging becomes impossible when variables are set or altered anywhere in the script.
Let's seek to be reasonably elegant with our scripting because: a) it's good form, and b) it leads to more easily understood scripts, which is the point of this column, right? So, get serious, and just change the function to return 0 on success and 1 on failure.
Now that you have a function you can expand later and have a way to return a true/false value to the calling script, how might it be utilized?
Here's one way:
if isdaytime ; then echo it is daytime else echo it is nighttime fi
Pretty trivial, but armed with this basic skeleton, let's have another look at the function itself.
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.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.
Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.
Sponsored by ActiveState
| Speed Up Your Web Site with Varnish | Jun 19, 2013 |
| Non-Linux FOSS: libnotify, OS X Style | Jun 18, 2013 |
| Containers—Not Virtual Machines—Are the Future Cloud | Jun 17, 2013 |
| Lock-Free Multi-Producer Multi-Consumer Queue on Ring Buffer | Jun 12, 2013 |
| Weechat, Irssi's Little Brother | Jun 11, 2013 |
| One Tail Just Isn't Enough | Jun 07, 2013 |
- Speed Up Your Web Site with Varnish
- Containers—Not Virtual Machines—Are the Future Cloud
- Linux Systems Administrator
- Lock-Free Multi-Producer Multi-Consumer Queue on Ring Buffer
- Non-Linux FOSS: libnotify, OS X Style
- Senior Perl Developer
- Technical Support Rep
- UX Designer
- Web & UI Developer (JavaScript & j Query)
- RSS Feeds
- Reply to comment | Linux Journal
1 hour 8 min ago - Reply to comment | Linux Journal
5 hours 8 min ago - Yeah, user namespaces are
6 hours 24 min ago - Cari Uang
9 hours 55 min ago - user namespaces
12 hours 49 min ago - yea
13 hours 15 min ago - One advantage with VMs
15 hours 43 min ago - about info
16 hours 16 min ago - info
16 hours 17 min ago - info
16 hours 18 min ago
Featured Jobs
| Linux Systems Administrator | Houston and Austin, Texas | Host Gator |
| Senior Perl Developer | Austin, Texas | Host Gator |
| Technical Support Rep | Houston and Austin, Texas | Host Gator |
| UX Designer | Austin, Texas | Host Gator |
| Web & UI Developer (JavaScript & j Query) | Austin, Texas | Host Gator |
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?




Comments
Dave -- your "Dealing with
Dave -- your "Dealing with Spaces in Filenames" column in the latest Linux Journal (cover date February 2011) ends by stating you would like to open the issue of spaces in filenames for discussion on the Linux Journal discussion boards.
I came here intending to add a suggestion to such a discussion ... but didn't find a thread specific to that topic.
Is there some place you would suggest I go?
Spaces in filenames
Dave, this is not relevant to this particular article, but rather to the general issue of handling spaces in filenames in bash scripts. A few years ago I was taught a drop-in replacement for the for / in loop that properly handles spaces in filenames. Once you reprogram your brain to use this instead of the for loop, you will be free to enter spaces in filenames at your leisure. Say you want to iterate over the output of the find command, in this case, files that end in .txt:
for f in `find . -name "*.txt" -type f`; do echo "file: $f"; done
A file with a single space will create two different lines. Instead, use the while read command:
find . -name "*.txt" -type f | while read f; do echo "file: $f"; done
Enjoy!
A couple nits
The statement
hour=$(date +%H)
should be
local hour=$(date +%H)
Otherwise, you're modifying the global variable $hour, and
any serious programmer knows it's bad form to have subroutines
or functions set or alter global variables.
And
function daytime
{
should be
daytime ()
{
if you care about being POSIX compliant. The former is a bash-ism and is not recognized by some shells (like dash).