11. 測試條件: test
#!/bin/bash
DAY=`date +%d`
if [ ${DAY} -eq 5 ]; then
echo " 發薪水囉! "
elif [ ${DAY} -ge 28 ]; then
echo " 沒錢了 ..."
else
echo " 過日子。 "
fi
重點: test , 中括號 [ ], if,
elif, then, -eq, -ge
●
test 搭配 if, while 等使用
●
條件判斷式
●
注意 if 的語法,分號的位
置
●
字串變數判斷方式要留意,
容易造成錯誤
12. 測試條件: test
●
常用的測試子
– ( ) : true, ! : not
– -a : and, -o : or
– 數 比較:值 -eq, -gt, -lt, -ge, -le, -ne
– 字串比較: =, !=
– 注意 = 與 -eq 的不同
– 字串判斷: -z, -n
– 常用 案判斷:檔 -b, -c, -d, -e, -f, -r, -w, -x
●
看一下男人吧! man test
13. 迴圈: while, until
#!/bin/bash
i=0
while [ $i -lt 10 ]; do
echo "i=$i"
let i+=1
done
#!/bin/bash
i=0
until [ $i -eq 10 ]; do
echo "i=$i"
let i+=1
done
重點: while, until 語法
14. 迴圈: for
#!/bin/bash
for FILENAME in /usr; do
echo "$FILENAME"
done
#!/bin/bash
for FILENAME in /usr/*; do
echo "$FILENAME"
done
重點: for 語法,還有元素內容
15. Exercise 2
●
找出 /usr/lib 中有幾個目錄、幾個執行 、幾個符號連結,還有檔
幾個其他的 案。檔
●
提示:
– man test
– 使用 for 迴圈
– 使用變數
– 使用 let 來增加變數值
16. 參考答案 2
#!/bin/bash
DIR=0
SYMLINK=0
EXEC=0
OTHER=0
for FILE in /usr/lib/*; do
if [ -d $FILE ]; then
let DIR+=1
elif [ -x $FILE ]; then
let EXEC+=1
elif [ -L $FILE ]; then
let SYMLINK+=1
else
let OTHER+=1
fi
done
echo "Dir:$DIR, Exec:
$EXEC, SYMLINK:
$SYMLINK, OTHER:$OTHER"
17. Bash Script 參數處理
#!/bin/bash
echo "0=$0, 1=$1, 2=$2"
if [ $1 = "Good" ]; then
echo "Thanks."
else
echo "Oops..."
fi
重點: $0, $1, $2
$0: 程式名稱
$1: 第一個參數
執行: ./test.sh Good ya
如果只輸入 ./test.sh ?呢