if [條件判斷式];then
#執行內容
fi#結束if
注意:if和[之間一定要有空格!不然會報語法錯誤
把多個條件寫入乙個判斷式
["$yn"=="y"-o"$yn"=="y"]
也可以用多個中括號隔開,等價於:
["$yn"=="y"]||["$yn"="y"]
例子:
path=/bin:/sbin
:/usr/bin
:/usr/sbin
:/usr/local/bin
:/usr/local/sbin
:~/bin
export path
read -p "please input (y/n): " yn
if [ "$yn" == "y" ] || [ "$yn" == "y" ]; then
echo "ok, continue"
exit 0
fiif [ "$yn" == "n" ] || [ "$yn" == "n" ]; then
echo "oh, interrupt!"
exit 0
fiecho "i don't know what your choice is" && exit 0
if ; then
elif ; then
else
fi
例1
read -p "please input (y/n): " yn
if [ "$yn" == "y" ] || [ "$yn" == "y" ]; then
echo
"ok, continue"
elif [ "$yn" == "n" ] || [ "$yn" == "n" ]; then
echo
"oh, interrupt!"
else
echo
"i don't know what your choice is"
fi
例2
# 1. 告知使用者這支程式的用途,並且告知應該如何輸入日期格式?
read -p "please input date of next friday (yyyymmdd ex>20090401): " date2
# 2. 測試輸入的內容是否正確
date_d=$(echo
$date2 |grep '[0-9]\') # 看看是否有八個數字
if [ "$date_d" == "" ]; then
echo
"you input the wrong date format...."
exit1fi
# 3. 計算日期
declare -i date_dem=`date --date="$date2" +%s` # 輸入日期秒數
declare -i date_now=`date +%s` # 現在日期秒數
#declare -i date_total_s=$(($date_dem-$date_now)) # 剩餘秒數統計
declare -i date_d=$(($date_total_s/60/60/24)) # 轉為日數
if [ "$date_total_s"
-lt"0" ]; then
echo
"your input is the friday passed: " $((-1*$date_d)) " ago"
else
declare -i date_h=$(($(($date_total_s-$date_d*60*60*24))/60/60))
echo
"the next friday will arrive after $date_d days and $date_h hours."
fi
注1*一定要接空格的地方:*
-grep後
-條件判斷式中的每一項
注2*declare:用來宣告和顯示已經存在的shell變數*
已知,既定的多個變數
case $變數名稱 in
"第乙個變數內容")
...;;
"第二個變數內容"
... ;;
*)#用*代表其他所有變數
... exit 1
;;esac
例2:
echo
"this program will print your selection !"
# read -p "input your choice: " choice # 暫時取消,可以替換!
# case $choice in # 暫時取消,可以替換!
case
$1in
# 現在使用,可以用上面兩行替換!
"one")
echo
"your choice is one"
;;"two")
echo
"your choice is two"
;;"three")
echo
"your choice is three"
;;*)
echo
"usage $0 "
;;esac
用『case $1 in』時,
source sh08.sh one
#在檔名後要帶引數
shell 條件判斷式
只要講到 程式 的話,那麼條件判斷式,亦即是 if then 這種判別式肯定一定要學習的!因為很多時候,我們都必須要依據某些資料來判斷程式該如何進行。這個 if then 是最常見的條件判斷式了 簡單的說,就是當符合某個條件判斷的時候,就予以進行某項工作就是了。這個 if then 的判斷還有多層次...
linux 條件判斷
1 case 語句 語法 case 變數 in 值1 程式 值2 程式 程式 在case語句中,以case開頭以esac結尾 每個分支程式中以雙分號結尾,表示程式結束 程式中的 表示其他所有值 2 if語句 語法 if 條件判斷式1 then 程式elif 條件判斷式2 then 程式else 程式...
Linux條件判斷
條件測試型別 整數測試 字元測試 檔案測試 條件測試的表示式 expression expression test expression整數比較 eq 測試兩個整數是否相等 比如 a eq b ne 測試兩個整數是否不等 不等,為真 相等,為假 gt 測試乙個數是否大於另乙個數 大於,為真 否則,為...