bash 的迴圈除了 for,還有 while 與 until 這對孿生兄弟:while 是「條件成立就繼續」,until 剛好相反,是「條件不成立就繼續」。兩者搭配 case,很適合做互動式的選單程式。
#!/bin/bash
#
cat << EOF
d|D) show disk usage
m|M) show memory usage
s|S) show swap usage
q|Q) quited
EOF
read Input
until [ $Input == q -o $Input == Q ];do
case $Input in
d|D)
df -h
echo " d|D) show disk usage"
echo " m|M) show memory usage"
echo " s|S) show swap usage"
echo " q|Q) quited"
read Input
;;
m|M)
free -m | grep 'Mem'
echo " d|D) show disk usage"
echo " m|M) show memory usage"
echo " s|S) show swap usage"
echo " q|Q) quited"
read Input
;;
s|S)
free -m | grep 'Swap'
echo " d|D) show disk usage"
echo " m|M) show memory usage"
echo " s|S) show swap usage"
echo " q|Q) quited"
read Input
;;
*)
echo "Usage: {[d|D],[m|M],[s|S],[q|Q]}"
read Input
;;
esac
done
這支程式的關鍵在於:每個分支的最後都要再 read 一次,否則迴圈條件永遠不會更新,程式就會卡在該分支裡出不來。這也是初學者寫互動選單時最常踩的坑。