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 />

#!/bin/bash<br />

# timeout.sh<br />

# Written by Stephane Chazelas,<br />

# and modified by the document author.<br />

INTERVAL=5<br />

# timeout interval<br />

timedout_read() {<br />

timeout=$1<br />

varname=$2<br />

old_tty_settings=`stty −g`<br />

stty −icanon min 0 time ${timeout}0<br />

eval read $varname # or just read $varname<br />

stty "$old_tty_settings"<br />

# See man page for "stty".<br />

}<br />

echo; echo −n "What's your name? Quick! "<br />

timedout_read $INTERVAL your_name<br />

# This may not work on every terminal type.<br />

# The maximum timeout depends on the terminal.<br />

# (it is often 25.5 seconds).<br />

echo<br />

if [ ! −z "$your_name" ] # If name input before timeout...<br />

then<br />

echo "Your name is $your_name."<br />

else<br />

echo "Timed out."<br />

fi<br />

echo<br />

# The behavior of this script differs somewhat from "timed−input.sh".<br />

# At each keystroke, the counter resets.<br />

exit 0<br />

Perhaps the simplest method is using the −t option to read.<br />

Example 9−4. Timed read<br />

#!/bin/bash<br />

# t−out.sh (per a suggestion by "syngin seven)<br />

TIMELIMIT=4<br />

# 4 seconds<br />

read −t $TIMELIMIT variable

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

Saved successfully!

Ooh no, something went wrong!