+ -
当前位置:首页 → 问答吧 → [和[[有什么不同

[和[[有什么不同

时间:2011-01-25

来源:互联网

以下是个人的一些总结,有不同意见欢迎讨论
  1. $ type [
  2. [ is a shell builtin
  3. $ type [[
  4. [[ is a shell keyword
复制代码
也就是说[处理里面的字串是当作参数来处理的,而[[对待其中的字串是当作表达式来处理的
那么当作参数和表达式有什么不同呢?

表达式中不会有wordsplitting 或者glob expansion,而参数处理会有
  1. $ ls
  2. file  file 1        #注意是2个文件(file 和file 1)
  3. $ (foo="file 1";[[ -f $foo ]]&&echo "$foo is a file")
  4. file 1 is a file

  5. ]$ (foo="file 1";[ -f $foo ]&&echo "$foo is a file")   # 这里file 1被分成2个word,所以出错
  6. bash: [: file: binary operator expected
复制代码
再来看看glob expansion
  1. $ touch '*'
  2. $ (foo="*";[ -f $foo ]&&echo "$foo is a file")   #为什么显示too many arguments,因为 *被扩展为所有目录下的文件
  3. bash: [: too many arguments
  4. $ (foo="*";[[ -f $foo ]]&&echo "$foo is a file")  # *被当成普通字符了
  5. * is a file
复制代码
参数传递中<和>会被解析成重定向符号,所以必须转义掉
  1. $ ([ "s" < "l" ]&&echo yes)              #错误使用
  2. bash: l: No such file or directory

  3. $ ([ "s" \> "l" ]&&echo yes)       #正确使用
  4. yes

  5. $ ([[ "s" > "l" ]]&&echo yes)     #而在表达式中比较符号不会被当作重定向符号
  6. yes
复制代码
参数传递中小括号会被分割成token,而在表达式中则会被解析成运算顺序
  1. $ ([ "s" \> "l" -a ( file "l" \> "a" -o "l" \> "p" ) ]&&echo yes)  #(和)必须被转义,以避免参数解析中的不正确分词
  2. bash: syntax error near unexpected token `('

  3. $ ([ "s" \> "l" -a \( "l" \> "a" -o "l" \> "p" \) ]&&echo yes)
  4. yes

  5. $ ([[ "s" > "l" && ( "l" > "a" || "l" > "p" ) ]]&&echo yes; ) #而表达式则不需要考虑这个
  6. yes
复制代码

作者: justlooks   发布时间: 2011-01-25

总结的很好。

作者: ly5066113   发布时间: 2011-01-25

收藏了……

作者: yinyuemi   发布时间: 2011-01-25