Shell脚本学习笔记-条件判断

1.  条件判断之if-then结构:

1.1 单条件,命令格式如下:

if command
then
      commands
fi

简单示例:

Shell脚本学习笔记-条件判断_第1张图片

1.2 全覆盖,命令格式如下:

if command
then
       commands
else
      commands
fi

1.3 条件嵌套,命令格式如下:

if command1
then
       if command2
       then
              commands
       fi
       commands
fi

1.4 多重条件判断,命令格式如下:

if command1
then
      commands
elif  command2
then
      commands
else
      commands
fi

2. 常用判断条件

2.1 数值比较

相等 : n1 -eq n2

大于等于: n1 -ge n2

大于:n1 -gt n2

小于等于:n1 -le n2

小于:n1 -lt n2

不等于: n1 -ne n2

简单示例:

Shell脚本学习笔记-条件判断_第2张图片

2.2 字符串比较 (其中字符串的大小比较,是根据ASCII码进行比较)

str1 = str2 : 

str1 != str2

str1 > str2

str1 < str2

-n str1

-z str1

简单示例:

Shell脚本学习笔记-条件判断_第3张图片

2.3 文件比较

-d file: 检查file是否存在并是一个目录

-e file: 检查file是否存在

-f file: 检查file是否存在并是一个文件

-s file: 检查file释放存在并非空

file1 -nt file2: 检查file1是否比file2新

file1 -ot file2: 检查file1是否比file2旧

-r file:  检查file是否存在并可读

-w file: 检查file是否存在并可写

-x file: 检查file是否存在并执行

-O file: 检查file是否存在并属于当前用户所有

-G file: 检查file是否存在并且默认组与当前用户相同

简单示例:

Shell脚本学习笔记-条件判断_第4张图片

2.4 高级判断

2.4.1 高级数学表达式判断,格式: (( expression ))

Shell脚本学习笔记-条件判断_第5张图片

2.4.2 高级字符串比较,格式: [[ expression ]]

Shell脚本学习笔记-条件判断_第6张图片

3. 条件判断之case结构

3.1 case语法格式:

 case variable in

pattern1 | pattern2) commands;;

pattern3) commands;;

*) default commands;;

esac

3.2 简单示例:

Shell脚本学习笔记-条件判断_第7张图片

你可能感兴趣的:(shell)