Shell 编程/使用控制语句的示例代码
外观
< Shell 编程
以下代码假设使用 bash 环境,并且存在 dialog 工具。$1 表示第一个参数的值。代码第 18 行的无限循环在长时间运行后会消耗内存。
#!/bin/bash # # Simple alarm clock # Author:mmmooonnnsssttteeerrr # GPL released time=`date +%H%M%S` default=060000 quit=false alarm=$1 help="Usage: alarm [%HH%MM%SS | default]\nDefault set to $default." if [ -z "$alarm" ]; then echo -e "$help" exit 1 fi if [ "$1" = "default" ]; then alarm=$default fi until [ "$quit" = "true" ]; do dialog --title "alarm2" --infobox "Current time(%H%M%S)=$time\nAlarm set at $alarm. Ctrl+c to exit." 4 40 sleep 1 time=`date +%H%M%S` if [ "$time" = "$alarm" ]; then snooze=true until [ snooze = false ]; do dialog --title "alarm2" --infobox "$alarm(%H%M%S) has arrived. Ctrl+c to exit." 3 70 echo -ne "\a" sleep 1 done quit=true fi done exit 0
这是一个另一个闹钟程序。这次代码更有效率,因为它使用了 sleep 命令而不是无限循环,因此内存泄漏的风险更小。代码第 7 行的 trap 命令捕获信号 INT(ctrl-c)并执行 cleanUp 函数作为后处理操作。
#!/bin/bash # Author: mmmooonnnsssttteeerrr # GPL cleanUp() { exit 1 } trap cleanUp INT help="Usage: alarm3 [%H] [%M]" if [ -z $2 ]; then echo $help exit 1 fi time=`date +%H` alarm=$1 sleepfor="" # Have to calculate how long to sleep. # Hours if [ $alarm -lt $time ]; then sleepfor=`expr 24 - $time + $alarm` sleepfor=`expr $sleepfor "*" 60` else sleepfor=`expr $alarm - $time` sleepfor=`expr $sleepfor "*" 60` fi # Minutes time=`date +%M` alarm=$2 if [ $alarm -lt $time ]; then sleepfor=`expr $(($sleepfor + 60 - $time + $alarm)) "*" 60` else sleepfor=`expr $(($sleepfor + $alarm - $time)) "*" 60` fi sleep $sleepfor soundAlarm() { for beep in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 do [ $beep = 20 ] && break echo -ne "\a" sleep 1 done } soundAlarm exit 0
实际上,这段代码是唯一一个可以作为闹钟正常工作的代码。它基于以下算法
If a_h<T_h then (24-T_h+a_h)+a_m-T_m If a_h>=T_h then (a_h-T_h)+a_m-T_m
其中 a_h 是 alarm_hour,T_h 是 Time_hour,a_m 是 alarm_minute,T_m 是 Time_minute。
#!/bin/bash # # Beeps at a given time accurate to +-1min # mmmooonnnsssttteeerrr # # GPL # alarm_hour=$1 alarm_min=$2 alarm_min=`expr $alarm_min "*" 60` time_hour=`date +%H` time_min=`date +%M` time_min=`expr $time_min "*" 60` if [ -z $2 ]; then echo "alarm [%H] [%M]" exit 1 fi trap `exit 1` INT if [ $alarm_hour -lt $time_hour ]; then x=`expr $((24-$time_hour+$alarm_hour)) "*" 3600` sleepfor=`expr $x + $alarm_min - $time_min` else y=`expr $((alarm_hour-time_hour)) "*" 3600` sleepfor=`expr $y + $alarm_min - $time_min` fi echo $sleepfor sleep $sleepfor for beep in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 do [ $beep = 20 ] && break echo -ne "\a" sleep 1 done exit 0