Shell中的单括号和双括号

1. 单括号[ ] 和 test

左括号[test本质是一样的,是shell的内部命令,所以><等会被解释为重定向符号,而不是比较符号:

1
2
3
4
bash-3.2$ type [ [[ test
[ is a shell builtin
[[ is a shell keyword
test is a shell builtin

右括号]表示判断结束,可以通过man [查看支持的判断语句:

1
$ man [

1.1 文件相关判断

  • -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.

1.2 字符串相关判断

  • 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.

1.3 整型判断

  • 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.

1.4 多个判断连接

  • ! 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.

2. 双括号[[ ]]

双括号是shell的关键字,会返回一个状态码,所以也可以作为判断条件使用。(更加通用)

  • [[支持字符串的模式匹配,=~支持正则匹配
  • [[返回状态码,所以可以与shell中的 &&||一起使用:
1
2
$ [[ 1 < 2 ]] && echo "1 < 2" || echo "1 >= 2"
1 < 2