1. if 條件判斷
if [ 條件 ]
then
command
else
command
fi
2. 互動選單 (case)
echo -e "提示訊息\c"
read VAR
case $VAR in
Y) command ;;
N) command ;;
*) command ;; # 預設處理
esac
3. 迴圈判斷 (while)
a=1
while [ "$a" = "1" ]
do
fileno=$(ls -l /list/filename* | wc -l)
if [ "$fileno" = "10" ]
then
a=10
command
else
a=1
sleep 300
fi
done
4. 數值比較運算子
| 運算子 | 含義 |
| -eq | 等於 |
| -ne | 不等於 |
| -lt | 小於 |
| -le | 小於等於 |
| -gt | 大於 |
| -ge | 大於等於 |
5. 檔案測試運算子
| 運算子 | 條件為真當... |
| -s file | 檔案大小 > 0 |
| -d file | 是目錄 |
| -e file | 檔案/目錄存在 |
| -r file | 存在且可讀 |
| -w file | 存在且可寫 |
| -x file | 存在且可執行 |
| -f file | 是一般檔案 |
6. 字串比較
[ "a" = "b" ] # 相等
[ "a" != "b" ] # 不相等
[ -z "str" ] # 字串長度為 0
[ -n "str" ] # 字串長度非 0
7. 常用文字處理指令
| 指令 | 用途 |
| grep pattern file | 過濾包含 pattern 的行 |
| grep -v pattern file | 過濾不包含 pattern 的行 |
| uniq -u | 只顯示不重複的行 |
| uniq -d | 只顯示重複的行 |
| sort | 排序 |
| paste -d";" f1 f2 | 合併兩檔案並以 ; 分隔 |
8. 算術運算
echo "2*3+4" | bc # 浮點運算
result=$(echo "scale=2; $i*100" | bc | awk -F. '{print $1}')
9. 網路測試與返回值判斷
ping -c 2 www.163.com # 測試 2 次
# 上一指令返回值判斷
[ $? -eq 0 ] && echo "成功" || echo "失敗"
10. 參數處理範例
XXXX=$(echo $1 | wc -c)
cat $HOME/list/file.txt >/dev/null 2>&1
OK=$?
if [ -z "$1" ] || [ "$XXXX" -lt 4 ] || [ "$OK" -ne 0 ]; then
echo "參數錯誤:未輸入/長度不足/檔案不存在"
exit 1
fi
11. 迴圈處理檔案每一行
line=1
for i in $(cat bb)
do
QQ=$(echo "scale=2; $i*100" | bc | awk -F. '{print $1}')
if [ "$QQ" -ge 75 ]; then
sed -n "${line}p" temp.1 >> bad.1
fi
line=$((line + 1))
done