Shell While 命令
2018-02-09 本文已影响12人
ShootHzj
while循环用于重复地执行一个命令列表
while [ CONDITION ]
do
command1
command2
...
...
commandN
done
当条件为真时,command1...commandN将被执行。比如,逐行地读取一个文件的内容,
while IFS= read -r line
do
command1 on $line
command2 on $line
...
commandN
done < "/path/to/file:
定义一个无限while循环可以使用如下三种命令
true不做任何事,表示成功
false不做任何事,总是返回退出状态码1
:命令,总是返回退出状态码0
1 while:
2 do
3 echo "Do something.."
4 echo "Hit [ CTRL+C ] to stop!"
5 sleep 3
6 done
一个样例while脚本
1 while :
2 do
3 clear #清理终端屏幕
4
5 echo "=========================================="
6 echo " MAIN - MENU "
7 echo "=========================================="
8 echo "1. Display date and time."
9 echo "2. Display system information."
10 echo "3. Display what users are doing."
11 echo "4. Exit"
12
13 read -p "Enter your choice [ 1 - 4 ]: " choice
14
15 echo $choice
16
17 case $choice in
18 1)
19 echo "Today is $(date +%Y-%m-%d)."
20 echo "Current time: $(date +%H:%M:%S)"
21 read -p "Press [Enter] key to continue..." readEnterKey
22 ;;
23 2)
24 uname -a
25 read -p "Press [Enter] key to continue..." readEnterKey
26 ;;
27 3)
28 w
29 read -p "Press [Enter] key to continue..." readEnterKey
30 ;;
31 4)
32 echo "Bye!"
33 exit 0
34 ;;
35 *)
36 echo "Error: Invalid option!"
37 read -p "Press [Enter] key to continue..." readEnterKey
38 ;;
39 esac
40
41 done