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
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- Designing Electronics with Linux
- New Products
- Linux Systems Administrator
- Senior Perl Developer
- Technical Support Rep
- UX Designer
- Web & UI Developer (JavaScript & j Query)
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Dynamic DNS—an Object Lesson in Problem Solving
- Using Salt Stack and Vagrant for Drupal Development
- Reply to comment | Linux Journal
7 hours 29 min ago - Dynamic DNS
8 hours 3 min ago - Reply to comment | Linux Journal
9 hours 1 min ago - Reply to comment | Linux Journal
9 hours 51 min ago - Not free anymore
13 hours 53 min ago - Great
17 hours 40 min ago - Reply to comment | Linux Journal
17 hours 48 min ago - Understanding the Linux Kernel
20 hours 3 min ago - General
22 hours 33 min ago - Kernel Problem
1 day 8 hours ago
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
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).