27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

exit 0<br />

$SECONDS<br />

The number of seconds the script has been running.<br />

#!/bin/bash<br />

TIME_LIMIT=10<br />

INTERVAL=1<br />

echo<br />

echo "Hit Control−C to exit before $TIME_LIMIT seconds."<br />

echo<br />

while [ "$SECONDS" −le "$TIME_LIMIT" ]<br />

do<br />

if [ "$SECONDS" −eq 1 ]<br />

then<br />

units=second<br />

else<br />

units=seconds<br />

fi<br />

echo "This script has been running $SECONDS $units."<br />

# On a slow or overburdened machine, the script may skip a count<br />

#+ every once in a while.<br />

sleep $INTERVAL<br />

done<br />

echo −e "\a" # Beep!<br />

exit 0<br />

$SHELLOPTS<br />

the list of enabled shell options, a readonly variable<br />

bash$ echo $SHELLOPTS<br />

braceexpand:hashall:histexpand:monitor:history:interactive−comments:emacs<br />

$SHLVL<br />

Shell level, how deeply Bash is nested. If, at the command line, $SHLVL is 1, then in a script it will<br />

increment to 2.<br />

$TMOUT<br />

If the $TMOUT environmental variable is set to a non−zero value time, then the shell prompt will time<br />

out after time seconds. This will cause a logout.<br />

Unfortunately, this works only while waiting for input at the shell prompt console or<br />

in an xterm. While it would be nice to speculate on the uses of this internal variable<br />

for timed input, for example in combination with read, $TMOUT does not work in that<br />

context and is virtually useless for shell scripting. (Reportedly the ksh version of a<br />

timed read does work.)<br />

Implementing timed input in a script is certainly possible, but may require complex machinations.<br />

One method is to set up a timing loop to signal the script when it times out. This also requires a signal<br />

handling routine to trap (see Example 30−5) the interrupt generated by the timing loop (whew!).<br />

Chapter 9. Variables Revisited 70

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!