歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> Linux命令之while - Bash中的While循環

Linux命令之while - Bash中的While循環

日期:2017/3/1 16:20:14   编辑:關於Linux
Linux命令之while - Bash中的While循環 用途說明 while循環是Shell中常用的語法結構,它與其他編程語言中的while有些類似,只是寫法有些不一樣罷了。 常用格式 格式一 while 條件; do 語句 done 格式二 死循環 while true do 語句 done 格式三 死循環 while : do 語句 done 格式四 死循環 while [ 1 ] do 語句 done 格式五 死循環 while [ 0 ] do 語句 done 使用示例 示例一 Bash代碼 COUNTER=0 while [ $COUNTER -lt 10 ]; do echo The counter is $COUNTER let COUNTER=COUNTER+1 done [root@jfht ~]# COUNTER=0 [root@jfht ~]# while [ $COUNTER -lt 10 ]; do > echo The counter is $COUNTER > let COUNTER=COUNTER+1 > done The counter is 0 The counter is 1 The counter is 2 The counter is 3 The counter is 4 The counter is 5 The counter is 6 The counter is 7 The counter is 8 The counter is 9 [root@jfht ~]# 這個while循環改用for循環更好些 Bash代碼 for ((COUNTER=0; COUNTER<10; ++COUNTER)) do echo The counter is $COUNTER done [root@jfht ~]# for ((COUNTER=0; COUNTER<10; ++COUNTER)) > do > echo The counter is $COUNTER > done The counter is 0 The counter is 1 The counter is 2 The counter is 3 The counter is 4 The counter is 5 The counter is 6 The counter is 7 The counter is 8 The counter is 9 [root@jfht ~]# 示例二 Bash代碼 while true do date sleep 1 done [root@jfht ~]# while true > do > date > sleep 1 > done 2010年 10月 10日 星期日 16:35:22 CST 2010年 10月 10日 星期日 16:35:23 CST 2010年 10月 10日 星期日 16:35:24 CST 2010年 10月 10日 星期日 16:35:25 CST 2010年 10月 10日 星期日 16:35:26 CST 2010年 10月 10日 星期日 16:35:27 CST Ctrl+C [root@jfht ~]# 示例三 讀取輸入 Java代碼 while read line do echo $line done [root@jfht ~]# while read line > do > echo $line > done hello hello world worldCtrl+D [root@jfht ~]# 實例四 處理命令行參數 文件 while_4.sh Bash代碼 #!/bin/sh usage() { echo "usage: $0 [-a] [-e <admin>] [-f <serverfile>] [-h] [-d <domain>] [-s <whois_server>] [-q] [-x <warndays>]" } while getopts ae:f:hd:s:qx: option do case "${option}" in a) ALARM="TRUE";; e) ADMIN=${OPTARG};; d) DOMAIN=${OPTARG};; f) SERVERFILE=$OPTARG;; s) WHOIS_SERVER=$OPTARG;; q) QUIET="TRUE";; x) WARNDAYS=$OPTARG;; \?) usage; exit 1;; esac done echo "ALARM=$ALARM" echo "ADMIN=$ADMIN" [root@jfht ~]# cat while_4.sh #!/bin/sh usage() { echo "usage: $0 [-a] [-e <admin>] [-f <serverfile>] [-h] [-d <domain>] [-s <whois_server>] [-q] [-x <warndays>]" } while getopts ae:f:hd:s:qx: option do case "${option}" in a) ALARM="TRUE";; e) ADMIN=${OPTARG};; d) DOMAIN=${OPTARG};; f) SERVERFILE=$OPTARG;; s) WHOIS_SERVER=$OPTARG;; q) QUIET="TRUE";; x) WARNDAYS=$OPTARG;; \?) usage; exit 1;; esac done echo "ALARM=$ALARM" echo "ADMIN=$ADMIN" [root@jfht ~]# chmod +x while_4.sh [root@jfht ~]# ./while_4.sh ALARM= ADMIN= [root@jfht ~]# ./while_4.sh -a ALARM=TRUE ADMIN= [root@jfht ~]# ./while_4.sh -e hy ALARM= ADMIN=hy [root@jfht ~]#
Copyright © Linux教程網 All Rights Reserved