bash腳本里定義後續命令執行日誌輸出路徑
#!/bin/bash logDir=`date +%F` exec &>/tmp/logDir.log //此次定義後續命令的執行輸出日誌路徑 df -h top
for循環
循環允許你重複一段代碼固定次數,在循環代碼執行期間,一個稱爲循環變量的特殊變量被賦予了不同的值;
for循環很適合處理命令行上的參數以及文件集,for結構的語法如下:
for name [in list]
do
statements
done
list爲名稱列表,如果in list被省略,列表默認爲"$@",即命令行參數的引用列表。
3. 練習
例如:
獲取執行腳本附帶的參數並輸出
for.sh:
#!/bin/bash for fileDir in "$@" do echo "$fileDir" done
執行
#bash for.sh /var /opt /tmp /var /opt /tmp
輸出1-n,n爲執行腳本帶入的參數
for2.sh:
#!/bin/bash for i in `seq $1` do echo "$i" done
執行:
#bash for2.sh 3 1 2 3
計算從1加到n爲多少,n爲你執行該腳本時帶入的參數?
vi for3.sh
#!/bin/bashfor for i in `seq $1` do let sum+=$i done echo "sum=$sum" 執行:#bash for3.sh 100 sum=5050
5秒倒計時
daojishi.sh #!/bin/bash n=5 for i in `seq 5` do echo "倒計時:$n" let n-- sleep 1 done 執行:#bash daojishi.sh 倒計時:5 倒計時:4 倒計時:3 倒計時:2 倒計時:1
階乘算法,10的階乘結果?
[craft@vp143 test]$ vi jiecheng.sh
#!/bin/bash
n=10
tmp=1
for i in `seq $n`
do
let tmp=`expr $i \* $tmp`
echo "$tmp"
done執行:[craft@vp143 test]$ bash -i jiecheng.sh
1
2
6
24
120
720
5040
40320
3628803628800