使用结构化命令

使用结构化命令

1.使用if-then语句

格式如下:
if commands
then
    commands
fi
bash shell的if语句会运行if后面的那个命令,如果该命令的退出状态
码为0,则执行then后面的命令,如果状态码是其他值,则if-then语句
就到此结束

2.if-then-else语句

if command
then
    commands
else
    commands
fi
前面的if-then使用规则一样,只是当if后面的command不为0时,则执行
ele后面的命令

3.嵌套if

if command1
then
    command
elif command2
then 
    command
.
.
.
elif comandn
then
    command
fi
每个then后面当然可以多条命令,shell会将他视为一个块

4.test命令

test命令提供了在if-then语句中测试不同条件的途径。如果test
命令中列出的条件成立,test命令就会退出并返回退出状态码0

列如:
#!/bin/bash
my_variable="Full"
if test $my_variable
then
    echo "The $my_variable expression returns a True"
else
    echo "False"
fi
这样在shell中执行,会输出The Full expression returns a True

test命令可以判断三类条件
数值比较
字符串比较
文件比较

bash shell 提供了另外一种条件测试方法
if [ condition ]
then
    commands
fi

5.数值比较

n1 -eq n2  检查n1是否等于n2
 -ge   大于或等于  
 -gt   大于
 -le   小于或等于
 -lt   小于
 -ne   不等于
 
 #!/bin/bash
 value1=10
 if[ $value1 -gt 5]
 then
    echo "The test value $value1 is greater than 5"
 fi
 
 输出The test value 10 is greater than 5

6.字符串比较

str1 = str2 检查str1与str2是否相同
等等
-n str1 检查str1长度是为非0
-z str1 检查str1长度是否为0
注意这些比较仅针对第一个字母

#!/bin/bash
str1="Full"
str2="Full2"
if[ $str1 -eq $str2]
then
    echo "euqal"
fi

输出euqal

7.文件比较

test –b File                                     文件存在并且是块设备文件
test –c File                                     文件存在并且是字符设备文件
test –d File                                     文件存在并且是目录
test –e File                                     文件存在
test –f File                                     文件存在并且是正规文件
test –g File                                     文件存在并且是设置了组ID
test –w File                                     文件存在并且可写
test –r File                                     文件存在并且可读
test –x File                                     文件存在并且可执行

8.case命令

case variable in
pattern1)
    command;;
pattern2)
    command;;
pattern3)
    command;;
*)
    command;;
esac
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

1egenda

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值