
Useful Elements for bash Scripts
|
225
To escape from a loop, use break. Let’s rewrite our until example as a while loop
with a
break:
#!/bin/bash
gameover="q"
while [[ true ]]
do
echo -n "Your commmand ($gameover to quit)? "
read cmd
if [[ $cmd == $gameover ]]; then break; fi
$cmd
done
To skip the rest of the loop and jump back to the start, use continue:
#!/bin/bash
gameover="q"
while [[ true ]]
do
echo -n "Your commmand ($gameover to quit)? "
read cmd
if [[ $cmd != $gameover ]]; then $cmd; continue; fi
break
done
cron Jobs
Shell scripts are often used to glue programs together. A common example in Linux
is the definition of cron jobs. cron is the standard Linux job scheduler. If you want
something to happen the third Tuesday of every month at the uncivilized hour of
01:23, you can get cron to do it for you without any of the negative feedback that
you would get from a person. The cron daemon checks every minute to see whether
it’s time to do something, or if any cron job specifications have changed.
You specify cron jobs by editing a crontab file. You can view the contents of your
crontab, if any, as follows:
admin@server1:~$ crontab -l
no crontab for admin
To edit your crontab, enter:
admin@server1:~$ crontab -e
Each line of a crontab file contains a day/time specification and a command, in this
format:
minute hour day_of_month month day_of_week command
This requires more than a little explanation:
•