bash while loop syntax

bash while loop syntax

The syntax is as follows:

while [ condition ]
do
command1
command2
command3
done


Good day! Is there any way to include a timer (timestamp?or whatever term it is) in a script using bash? Like for instance; every 60 seconds, a specific function checks if the internet is down, if it is, then it connects to the wifi device instead and vice versa. In short, the program checks the internet connection from time to time.

Any suggestions/answers will be much appreciated. =)

 

Blunt version

while sleep 60;do
 
if! check_internet;then
   
if is_wifi;then
       set_wired
   
else
       set_wifi
   
fi
 
fi
done



You can do something like the following, but it is not reliable:

#!/bin/sh

trap handle_timer USR1

set_timer() { (sleep 2; kill -USR1 $$)& }
handle_timer() {
printf "%s:%s\n" "timer expired" "$(date)";
set_timer
}

set_timer
while true; do sleep 1; date; done

One problem with this technique is that the trap will not take effect until the current task returns to the shell (eg, replace the sleep 1 with sleep 10). If the shell is in control most of the time (eg if all the commands it calls will terminate quickly), this can work. One option of course, is to run everything in the background.

 

#!/bin/bash
i=1
y=1
while [ $i -le 5 ]
do
while [ $y -le 10 ]
do
echo "$y * $i = $(( $y * $i ))"
(( y++ ))
done
y=1
(( i++ ))
done


posted @ 2012-08-07 15:06  alxe_yu  阅读(220)  评论(0)    收藏  举报