左括号[
和test
本质是一样的,是shell的内部命令,所以>
和<
等会被解释为重定向符号,而不是比较符号:
bash-3.2$ type [ [[ test [ is a shell builtin [[ is a shell keyword test is a shell builtin
右括号]
表示判断结束,可以通过man [
查看支持的判断语句:
$ man [
-d file
: True if file exists and is a directory.-f file
: True if file exists and is a regular file.-h file
: True if file exists and is a symbolic link.-S file
: True if file exists and is a socket.file1 -nt file2
: True if file1 exists and is newer than file2.string
: True if string is not the null string.s1 = s2
: True if the strings s1 and s2 are identical.s1 < s2
: True if string s1 comes before s2 based on the binary value of their characters.n1 -eq n2
: True if the integers n1 and n2 are algebraically equal.n1 -ne n2
: True if the integers n1 and n2 are not algebraically equal.n1 -gt n2
: True if the integer n1 is algebraically greater than the integer n2.n1 -ge n2
: True if the integer n1 is algebraically greater than or equal to the integer n2.n1 -lt n2
: True if the integer n1 is algebraically less than the integer n2.n1 -le n2
: True if the integer n1 is algebraically less than or equal to the integer n2.! expression
: True if expression is false.expression1 -a expression2
: True if both expression1 and expression2 are true.expression1 -o expression2
: True if either expression1 or expression2 are true.双括号是shell的关键字,会返回一个状态码,所以也可以作为判断条件使用。(更加通用)
[[
支持字符串的模式匹配,=~
支持正则匹配[[
返回状态码,所以可以与shell中的 &&
和||
一起使用:$ [[ 1 < 2 ]] && echo "1 < 2" || echo "1 >= 2" 1 < 2