if … then …
简单条件判断式:
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
fi
if [ "$yn" == "N" ] || [ "$yn" == "n" ]; then
echo "Oh, interrupt!"
exit 0
fi
echo "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]\{8\}') # 看看是否有八个数字
if [ "$date_d" == "" ]; then
echo "You input the wrong date format...."
exit 1
fi
# 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…..esac
已知,既定的多个变量
case $变量名称 in
"第一个变量内容")
...
;;
"第二个变量内容"
...
;;
*)#用*代表其他所有变量
...
exit 1
;;
esac
例2:
echo "This program will print your selection !"
# read -p "Input your choice: " choice # 暂时取消,可以替换!
# case $choice in # 暂时取消,可以替换!
case $1 in # 现在使用,可以用上面两行替换!
"one")
echo "Your choice is ONE"
;;
"two")
echo "Your choice is TWO"
;;
"three")
echo "Your choice is THREE"
;;
*)
echo "Usage $0 {one|two|three}"
;;
esac
用‘case $1 in’时,
source sh08.sh one
#在文件名后要带参数
本文介绍了Linux中的条件判断式,包括简单条件判断的语法,注意要点如if与[之间的空格,以及如何构建多重复杂条件判断。同时讲解了case…esac结构,展示了如何处理已知变量的多个情况。

1万+

被折叠的 条评论
为什么被折叠?



