9.3.6  条件表达式

更新于 2026年10月13日 版权声明
9.3.6 条件表达式

(1)算术测试

运算符:

﹤=、﹥=、﹤、﹥ ;小于等于、大于等于、小于、大于

==、!= ;相等、不相等

! ;逻辑非

&& ;逻辑与

|| ;逻辑或

算术测试用(()),例如:

If(($result==0))

While(($count﹤=$testval));do

(())内变量名前可以不用$。

(2)字符串比较

字符串条件运算符:

-n string ;字符串长度不为0

-z string ;字符串长度为0

sring1==string2 ;字符串相等为真

string1!=string2 ;字符串不相等为真(https://www.daowen.com)

例如:

$a=abc

$if[-n$a] ;then echo a is not empty;fi

a is not empty

注意:字符串比较用方括号,括号、变量、运算符之间必须有空格,否则出错!

(3)面向文件表达式

-e file ;若文件存在则为真

-f file ;若文件存在且是普通文件为真

-r file ;若文件存在且可读为真

-w file ;若文件存在且可写为真

-x file ;若文件存在且可写为真

-d file ;若文件存在且是目录则为真

例如:

$mkdir a

$if[-d a];then echo a is a directory;fi

a is a directory

测试也是用[],且与变量符号之间必须有空格分隔。

✍AI写作