如何修改网站元素,网站快速刷排名工具,做网站腾讯云服务器,沈阳网页设计培训if 语句
if 语句是 Shell 脚本中用于条件判断的基本结构。
基本语法
if 语句的基本语法如下#xff1a;
if [ condition ]
thencommands
ficondition 是要测试的条件。commands 是在条件为真时要执行的命令。
示例
简单条件判断
#!/bin/bashif [ 1 -eq 1 ]
thenecho
if [ condition ]
thencommands
ficondition 是要测试的条件。commands 是在条件为真时要执行的命令。
示例
简单条件判断
#!/bin/bashif [ 1 -eq 1 ]
thenecho 1 is equal to 1
fiif-else 语句
if-else 语句允许你在条件为假时执行其他命令。
#!/bin/bashif [ 1 -eq 2 ]
thenecho This will not be printed
elseecho 1 is not equal to 2
fiif-elif-else 语句
if-elif-else 语句允许你测试多个条件。
#!/bin/bashnum3if [ $num -eq 1 ]
thenecho The number is 1
elif [ $num -eq 2 ]
thenecho The number is 2
elseecho The number is neither 1 nor 2
fi条件测试
数值比较
-eq等于-ne不等于-lt小于-le小于等于-gt大于-ge大于等于
#!/bin/basha5
b10if [ $a -lt $b ]
thenecho $a is less than $b
fi字符串比较
等于!不等于小于在 ASCII 顺序上大于在 ASCII 顺序上-z字符串为空-n字符串不为空
#!/bin/bashstr1hello
str2worldif [ $str1 $str2 ]
thenecho The strings are equal
elseecho The strings are not equal
fi文件测试
-e filename文件存在-r filename文件可读-w filename文件可写-x filename文件可执行-d filename文件是目录-f filename文件是普通文件-s filename文件非空
#!/bin/bashfiletest.txtif [ -e $file ]
thenecho File exists
elseecho File does not exist
fi