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 is the author of the popular Work the Shell column in Linux Journal.
Trending Topics
| Make TV Awesome with Bluecop | May 16, 2012 |
| Hack and / - Password Cracking with GPUs, Part I: the Setup | May 15, 2012 |
| An Introduction to Application Development with Catalyst and Perl | May 14, 2012 |
| Cryptocurrency: Your Total Cost Is 01001010010 | May 09, 2012 |
| HTML5 for Audio Applications | May 07, 2012 |
| May 2012 Issue of Linux Journal: Programming | May 02, 2012 |
- Hack and / - Password Cracking with GPUs, Part I: the Setup
- An Introduction to Application Development with Catalyst and Perl
- Validate an E-Mail Address with PHP, the Right Way
- Monitoring Hard Disks with SMART
- Readers' Choice Awards 2011
- Which one is the Best Free and Paid PDF editor for Mac
- Examining Load Average
- Bash Regular Expressions
- Building an Ultra-Low-Power File Server with the Trim-Slice
- Python for Android
- It's true that maintaining
1 hour 59 min ago - as powerful as anything the
7 hours 36 min ago - Excellent!
10 hours 59 min ago - You can mount ext2 and ext3
18 hours 46 min ago - Awsome Post
1 day 7 hours ago - Math Worksheets
1 day 11 hours ago - Healthy eating effective weight loss of p57
1 day 16 hours ago - Good work, looking for more!
1 day 16 hours ago - I’ve been reading a number of
1 day 18 hours ago - With freeware SKim, You can
1 day 18 hours ago






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).