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.

Example 9−2. Timed Input<br />

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

#!/bin/bash<br />

# timed−input.sh<br />

# TMOUT=3 useless in a script<br />

TIMELIMIT=3 # Three seconds in this instance, may be set to different value.<br />

PrintAnswer()<br />

{<br />

if [ "$answer" = TIMEOUT ]<br />

then<br />

echo $answer<br />

else # Don't want to mix up the two instances.<br />

echo "Your favorite veggie is $answer"<br />

kill $! # Kills no longer needed TimerOn function running in background.<br />

# $! is PID of last job running in background.<br />

fi<br />

}<br />

TimerOn()<br />

{<br />

sleep $TIMELIMIT && kill −s 14 $$ &<br />

# Waits 3 seconds, then sends sigalarm to script.<br />

}<br />

Int14Vector()<br />

{<br />

answer="TIMEOUT"<br />

PrintAnswer<br />

exit 14<br />

}<br />

trap Int14Vector 14<br />

# Timer interrupt (14) subverted for our purposes.<br />

echo "What is your favorite vegetable "<br />

TimerOn<br />

read answer<br />

PrintAnswer<br />

# Admittedly, this is a kludgy implementation of timed input,<br />

#+ however the "−t" option to "read" simplifies this task.<br />

# See "t−out.sh", below.<br />

# If you need something really elegant...<br />

#+ consider writing the application in C or C++,<br />

#+ using appropriate library functions, such as 'alarm' and 'setitimer'.<br />

exit 0<br />

An alternative is using stty.<br />

Example 9−3. Once more, timed input<br />

Chapter 9. Variables Revisited 71

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

Saved successfully!

Ooh no, something went wrong!