【shell】shell学习笔记,结构化命令,if-then语句

if-then语句

if command

then

  commands

commands

fi

if-then-else语句

if command

then

  commands

else

  commands

fi

嵌套if

if command1

then

  commands

elif command2

then

  more commands

fi

test命令

if [ condition ]

then

  commands

fi

test 命令的数值比较功能

n1 -eq n2 检查n1是否与n2相等

n1 -ge n2 检查n1是否大于或等于n2

n1 -gt n2 检查n1是否大于n2

n1 -le n2 检查n1是否小于或等于n2

n1 -lt n2 检查n1是否小于n2

n1 -ne n2 检查n1是否不等于n2

字符串比较

test命令的字符串比较功能

str1 = str2 检查str1是否和str2相同

str1 !=str2 检查str1是否和str2不同

str1 < str2 检查str1是否比str2小

str1 > str2 检查str1是否比str2大

-n str1 检查str1的长度是否非0

-z str1 检查str1的长度是否为0

例子:

#!/bin/bash
#string comparisons

val1=aaaaaaa
val2=aaa

if [ $val1 > $val2 ]

#比较符号前需要加反斜杠,否则会被当做重定向处理
then
    echo "$val1 is greater than $val2"
else
    echo "$val1 is less than $val2"
fi

if [ -n "$val1" ]

#判断字符串长度是否非零

if [ -z "$val2" ]

#判断字符串长度是否为零

*文件比较

test命令的文件比较功能

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

-e file 检查file是否存在

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

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

-s file 检查file是否存在并非空

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

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

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

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

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

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

复合条件测试

[ condition1 ] && [ condition2 ]

[ condition1 ] || [ condition2 ]

使用双圆括号

双圆括号允许将高级数学表达式放入比较中。

双圆括号命令符号

val++ 后增

val-- 后减

++val 先增

--val 先减

! 逻辑求反

~ 位求反

** 幂运算

<< 左位移

>> 右位移

& 位布尔和

| 位布尔或

&& 逻辑和

|| 逻辑或

#双圆括号中的大于小于号不需要转义

使用双方括号

[[ expression ]]

双方括号提供了test命令另一个特性-模式匹配

在模式匹配中,可以定义一个正则表达式来匹配字符串值

case命令

case variable in

pattern1 | pattern2) command1;;

pattern3) command2;;

*) defalt commands;;

esac

原文地址:https://www.cnblogs.com/powercool/p/6943748.html