Educating yourself does not mean that you were stupid in the first place; it means that you are intelligent enough to know that there is plenty left to 'learn'. -Melanie Joy

Thursday 4 October 2012

Timeout - timed wait in shell scripting

October 04, 2012 Posted by Dinesh , , No comments
TMOUT is the shell built in variable to set the timeout .

TMOUT is used in three different ways: by the read builtin command, by the select builtin, and by the interactive bash shell. If it is unset, or equal to zero, then it is ignored. If it has any positive value, then these three commands which make use of it will timeout after $TMOUT seconds.

Example:
$> cat timeout.sh


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#!/bin/bash

TMOUT=5
read -p "Enter password : " pass
if [ $? -eq 0 ]
then
   echo "Password is $pass"
  else
    echo "Timed out...."
fi



same effect can be achieved using read with -t option.
read -t 5 -p "Enter password : " pass


PIPESTATUS and its Alternative

October 04, 2012 Posted by Dinesh , , No comments
$> cat /etc/hosts | grep 000.000
$> $?
1


$> cat /etc/hosts | grep 000.000 | uniq
$> $?
0

Why is it returning success (0) though it fails during grep ??
the return code of a pipeline will be that of the return status of the rightmost command .
How to resolve this ??
use inbuilt PIPESTATUS variable.

PIPESTATUS is a array variable which contain the exit status of each command in piped commands. 

$> cat /etc/hosts | grep 000.000 | uniq
$> echo ${PIPESTATUS[*]}
0 1 0

here $PIPESTATUS[0] contains the exit status of cat /etc/hosts command
$PIPESTATUS[1] contains the exit status of grep 000.000
$PIPESTATUS[2] contains the exit status of uniq


The other way around for this is setting pipefail.

$> set -o pipefail
$> cat /etc/hosts | grep 000.000 | uniq
$> $?
1