您的位置:首页 > 运维架构 > Shell

shell脚本编程基础(二)----使用结构化命令

2018-02-28 13:43 691 查看

if-then 语句

if command
then
commands
fi
如果该命令退出状态码是0  则执行then部分
另一种    : 
if command ; then
commands
fi

if-then-else

if command
then
    commands
else
    commands
fi

嵌套if

if command1
then
    commands
elif  command2
then
   commands
fi

test命令

test  condition 

condition条件为真  则返回退出状态码0

数值比较

例子: n1 -eq n2  是否相等

字符串比较

str1 = str2
str1 != str2
str1 > str2
-n   长度是否非0   ;   -z  长度是否为0

大于小于必须转义    \>   \<

文件比较

-d  是否存在并是一个目录
-e  是否存在
-f   是否十一个文件
-r  是否可读
-w    是否可写
-s     是否为空
-x    是否可执行
-O     是否为文件属主
-G     是否匹配用户的默认组
-nt   一个文件是否比另一个新
-ot    旧

复合条件测试

[ condition ] && [ condition ]
||

if - then  的高级特性

使用双括号 允许比较过程中使用高级数学表达式
(( expression )) 

包括    val++   val--   !   >>  &  等等 常见运算符

不需要转义

使用双方括号
[[ expression ]]   针对 字符串比较.  可以使用模式匹配 (正则表达式)

case命令

case  var  in
pattern1 | pattern2 ) command1 ;;
pattern3 ) command2 ;;
*) default commands ;;
esac



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: