October
27, 2003 -
Useful
Shell Scripting Variables - Part V -
SECONDS
|
|
Like
last week's environment variable, 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
8
38
$
|
|
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
10
40
$
|
|
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:
|
#!/bin/ksh
FILELIST="file1 file2 file3"
sleeptime=5
for i in ${FILELIST}
do
# record the value of SECONDS before
processing begins
start=$SECONDS
print "Processing $i..."
# Normally, processing statements would replace
# the following sleep statement
sleep ${sleeptime}
# record the value of SECONDS after
processing ends
stop=$SECONDS
# 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 ))
done
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.
|
|
|
|
|
|
|
Learn
more...
If you are new to the UNIX or Linux
operating system and would like to learn
more, you may want to consider
registering for LiveFire Labs' UNIX
and Linux Operating System Fundamentals
online training course.
If you already have a solid grasp of the
fundamentals but would like to learn more
about the Korn shell and basic and
advanced shell scripting, taking our Korn
Shell Scripting course will be
beneficial to you.
Our
innovative hands-on training model allows
you to learn
UNIX by completing hands-on
exercises on real servers in our Internet
Lab.
More
Tips...
· Popular
UNIX Tips from the Past
|
|