shell中的if主要是用于程序的判斷邏輯,從而控制腳本的執行邏輯。這和很多編程語言思路上都是一致的。
1、if的用法結構如下:
if exp;then
command1;
command2;
fi
示例:
#根據輸入的學生成績打印對應的成績等級:大于90分為優秀;大于80分良好,60到80分為及格;小于60分為差。
cat test.sh
#!/bin/bash
read -p "請輸入分數:" Score
if [ "$Score" -ge 90 ]; then
echo "優秀"
fi
if [ "$Score" -ge 80 ]; then
echo "良好"
fi
if [ "$Score" -ge 60 -a "$Score" -lt 80 ]; then
echo "及格"
fi
if [ "$Score" -lt 60 ]; then
echo "差"
fi
運行如下:輸入:88
輸出:良好
輸入:99
輸出:優秀
2、if/else結構用法
語法結構:
if exp; then
command
else?
command
fi
示例:#判斷某個文件是否存在
cat checkfile.sh
腳本內容如下:
#!/bin/bash
fl=/root/hgm/bash.sh
f2=/root/hgm/bash00.sh
if [ -e $f1 ];then
echo "$f1 存在"
else
echo "$f1 不存在"
fi
if [ -e $f2 ];then
echo "$f2 存在"
else
echo "$f2 不存在"
fi
bash checkfile.sh
輸出結果:
?存在
/root/hgm/bash00.sh 不存在
2、if/elif/else結構用法
語法格式:
if exp1; then
command1
elseif exp2;then
command2
elseif exp3;then
command3
...
fi
具體用法和上面兩種很相似不再舉例說明