Loops in shell scripts

Slashdot it! Delicious Share on Facebook Tweet! Digg!

Trigger Actions

You may not always want to use at or cron to perform an action at a certain date or time. You might want a shell script to do it.

The example shows a solution where a web browser exits without discussion after an hour's time. You could take this further, for example, by ending your child's session or even shutting down their computer. This also works for a small Internet café on your premises.

Listing 14 shows how it works. The start and end times are first defined. For simplicity's sake, the shell script is intentionally unfair – that means someone starting at minute one gets more time than someone else starting later on.

Listing 14

closingdown.sh

01 #! /bin/sh
02
03 # Hour when application is launched
04 start_time=$(date +%H)
05
06 # An hour later (taking day transition into account)
07 if [ $start_time -eq 23 ];
08   then
09        endhour=0
10   else
11        endhour=$(echo $start_time +  1 | bc)
12 fi
13
14 # Start program
15 firefox &
16
17 # Read PID
18 pid=$(echo $!)
19
20 # Control loop
21
22 while true;
23 do
24
25 # Current hour
26 hr=$(date +%H)
27
28 # If hr matches endhour, quit browser
29 if [ $hr -eq $endhour ];
30 then
31     kill -9 $pid
32     exit
33 fi
34 # Wait 59 seconds
35 sleep 59
36 done

Next, the browser is started and its process ID is stored in a variable. In the while true loop, a time test is performed every 59 seconds. Then, if the "closing hour" and current hour match, the browser process and script are terminated.

As these examples have shown, shell loops can be very useful if you take the time to understand their syntax and applications.

Buy this article as PDF

Express-Checkout as PDF

Pages: 5

Price $0.99
(incl. VAT)

Buy Ubuntu User

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content