在編程語言中,循環語句是最基本的語法之一,在Shell(這裏是Bash)中也不例外。
這裏包括for/while/until循環,以及變量自增的語法實例。
Shell(以Bash爲例)中的循環語句一般有for、while、until這幾種。
一、for循環語句
實例1.1 最基本的for循環: (傳統的形式,for var in …)
#!/bin/bash
for x in one two three four
do
echo number $x
done
注:”for” 循環總是接收 “in” 語句之後的某種類型的字列表。在本例中,指定了四個英語單詞,但是字列表也可以引用磁盤上的文件,甚至文件通配符。
實例1.2 對目錄中的文件做for循環
#!/bin/bash
for x in /var/log/*
do
#echo "$x is a file living in /var/log"
echo $(basename $x) is a file living in /var/log
done
注:這個$x獲得的是絕對路徑文件名;可以使用 “basename” 可執行程序來除去前面的路徑信息。如果只引用當前工作目錄中的文件(例如,如果輸入 “for x in *”),則產生的文件列表將沒有路徑信息的前綴。
實例1.3 對位置參數做for循環
#!/bin/bash
for thing in "$@"
do
echo you typed ${thing}.
done
實例1.4 for循環中用seq產生循環次數,加上C語言形式的for循環語句
#!/bin/bash
echo "for: Traditional form: for var in ..."
for j in $(seq 1 5)
do
echo $j
done
echo "for: C language form: for (( exp1; exp2; exp3 ))"
for (( i=1; i<=5; i++ ))
do
echo "i=$i"
done
注:對於固定次數的循環,可以通過seq命令來實現,就不需要變量的自增了;這裏的C語言for循環風格是挺熟悉的吧。
二、while循環語句
實例2.1 循環輸出1到10的數字
#!/bin/bash
myvar=1
while [ $myvar -le 10 ]
do
echo $myvar
myvar=$(( $myvar + 1 ))
done
注:只要特定條件爲真,”while” 語句就會執行;
-eq 等於;
-ne 不等於;
-gt 大於;
-ge 大於等於;
-lt 小於;
-le 小於等於;
若while無限次循環,通常有幾種寫法:
-
while [ 1 -eq 1 ]
-
or
-
while true
-
or
-
while ((1))
-
or
-
while [[ 1 ]]
-
or
- while :
三、until循環語句
實例3.1 循環輸出1到10的數字
“Until” 語句提供了與 “while” 語句相反的功能:只要特定條件爲假,它們就重複。下面是一個與前面的 “while” 循環具有同等功能的 “until” 循環。
#!/bin/bash
myvar=1
until [ $myvar -gt 10 ]
do
echo $myvar
myvar=$(( $myvar + 1 ))
done
我所知道的,bash中,變量自增,目前有五種方法:
1. i=`expr $i + 1`;
2. let i+=1;
3. ((i++));
4. i=$[$i+1];
5. i=$(( $i + 1 ))
可以實踐一下,簡單的實例如下:
#!/bin/bash
i=0;
while [ $i -lt 4 ];
do
echo $i;
i=`expr $i + 1`;
# let i+=1;
# ((i++));
# i=$[$i+1];
# i=$(( $i + 1 ))
done