LiveFire Labs: Online UNIX Training with Hands-on Internet Lab

"Taking a LiveFire Labs' course is an excellent way to learn Linux/Unix. The lessons are well thought out, the material is explained thoroughly, and you get to perform exercises on a real Linux/Unix box. It was money well spent."

Ray S.
Pembrook Pines, Florida

LiveFire Labs' UNIX and Linux Operating System Fundamentals course was very enjoyable. Although I regularly used UNIX systems for 16 years, I haven't done so since 2000. This course was a great refresher. The exercises were fun and helped me gain a real feel for working with UNIX/Linux OS. Thanks very much!"

Ming Sabourin
Senior Technical Writer
Nuance Communications, Inc.
Montréal, Canada

Read more student testimonials...

Receive UNIX Tips, Tricks, and Shell Scripts by Email

Custom Search

LiveFire Labs' UNIX Tip, Trick, or Shell Script of the Week

Useful Shell Script Variables - Part V - SECONDS

Like last week's shell script variable RANDOM, this week's variable also provides a different value each time it's referenced.  The value stored in SECONDS indicates the number of seconds since the shell was invoked:

$ print $SECONDS; sleep 30; print $SECONDS

If a value is assigned to SECONDS, the sum of that value and the number of seconds since its assignment is displayed when the variable is referenced:

$ SECONDS=10; print $SECONDS; sleep 30; print $SECONDS

One possible use for this variable is to time how long a particular operation within your shell script takes to complete.  For example, you may want to know how long it takes to process a unique set of data during each pass through a loop construct.  The following  script illustrates this concept:


FILELIST="file1 file2 file3"


for i in ${FILELIST}
  # record the value of SECONDS before processing begins

  print "Processing $i..."

  # Normally, processing statements would replace
  # the following sleep statement
  sleep ${sleeptime}

  # record the value of SECONDS after processing ends

  # calculate processing time
  (( runtime=stop-start ))
  print "Processing time for $i was $runtime seconds.\n"

  # increase the sleep time for next iteration of the loop
  (( sleeptime=sleeptime*2 ))


exit 0

Running this script produces the following output:

$ ./seconds
Processing file1...
Processing time for file1 was 5 seconds.

Processing file2...
Processing time for file2 was 10 seconds.

Processing file3...
Processing time for file3 was 20 seconds.


To provide a unique "runtime" value for each time through the loop in this script, the amount of time to sleep is doubled at the end of each iteration.  In an actual script, the counter and sleep statement may or may not be needed.

After the runtime is calculated, arithmetic statements can be added to convert the seconds to minutes if desired.