Work the Shell - Function Return Codes and Daylight Calculations

 in
Determining whether it's night or day (using bash, of course).

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.

Figuring Out Daylight Hours

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.

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Dave -- your "Dealing with

pj's picture

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

jtshoe's picture

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

Michael Cook's picture

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

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix