linux之条件判断if命令详解
linux之条件判断if命令详解if命令用于分支判断,有其固定的写法,与c语言等其他编程语言的条件判断逻辑一致,只是写法上稍微有点差别。if命令的写法:if 判断条件;thencommand1elif 判断条件;thencommand2elsecommand3fi因为多个命令写在同一行需要用分号分开,其实也可以这样写:if 判断条件thencommand1elif 判断条件thencommand2
linux之条件判断if命令详解
if命令用于分支判断,有其固定的写法,与c语言等其他编程语言的条件判断逻辑一致,只是写法上稍微有点差别。
if命令的写法:
if 判断条件;then
command1
elif 判断条件;then
command2
else
command3
fi
因为多个命令写在同一行需要用分号分开,其实也可以这样写:
if 判断条件
then
command1
elif 判断条件
then
command2
else
command3
fi
其中判断条件可以是[ ]、[[ ]]、test等,返回值是0或者1
具体可参考:
linux之
、
[
]
、
{ }、[ ]、
、[]、( )、
[
]
、
[ ]、
[]、(( ))、[[ ]]、(( ))的作用
linux之test命令详解
案例1:
if [ $1 -gt 5 ];then
echo "$1的值大于5"
elif [ $1 -eq 5 ];then
echo "$1的值等于5"
else
echo "$1的值小于5"
fi
案例2:
if [[ $1 > 5 ]];then
echo "$1的值大于5"
elif [[ $1 == 5 ]];then
echo "$1的值等于5"
else
echo "$1的值小于5"
fi
案例3:从命令行获取路径参数并且判断当前路径是否存在,如果存在判断文件类型
if test -e ./$1;then
echo "当前目录下$1存在"
if test -f ./$1;then
echo "$1是文件类型!"
elif test -d ./$1;then
echo "$1是文件夹类型!"
else
echo "$1既不是文件也不是文件夹!"
fi
else
echo "当前目录下$1不存在"
fi
if语句没有太多复杂的逻辑和变化,最多也就是嵌套条件判断,需要注意的是以if开头以fi结尾,结构要完整。
更多推荐
所有评论(0)