- 论坛徽章:
- 0
|
以下是个人的一些总结,有不同意见欢迎讨论
- $ type [
- [ is a shell builtin
- $ type [[
- [[ is a shell keyword
复制代码 也就是说[处理里面的字串是当作参数来处理的,而[[对待其中的字串是当作表达式来处理的
那么当作参数和表达式有什么不同呢?
表达式中不会有wordsplitting 或者glob expansion,而参数处理会有
- $ ls
- file file 1 #注意是2个文件(file 和file 1)
- $ (foo="file 1";[[ -f $foo ]]&&echo "$foo is a file")
- file 1 is a file
- ]$ (foo="file 1";[ -f $foo ]&&echo "$foo is a file") # 这里file 1被分成2个word,所以出错
- bash: [: file: binary operator expected
复制代码 再来看看glob expansion
- $ touch '*'
- $ (foo="*";[ -f $foo ]&&echo "$foo is a file") #为什么显示too many arguments,因为 *被扩展为所有目录下的文件
- bash: [: too many arguments
- $ (foo="*";[[ -f $foo ]]&&echo "$foo is a file") # *被当成普通字符了
- * is a file
复制代码 参数传递中<和>会被解析成重定向符号,所以必须转义掉
- $ ([ "s" < "l" ]&&echo yes) #错误使用
- bash: l: No such file or directory
- $ ([ "s" \> "l" ]&&echo yes) #正确使用
- yes
- $ ([[ "s" > "l" ]]&&echo yes) #而在表达式中比较符号不会被当作重定向符号
- yes
复制代码 参数传递中小括号会被分割成token,而在表达式中则会被解析成运算顺序
- $ ([ "s" \> "l" -a ( file "l" \> "a" -o "l" \> "p" ) ]&&echo yes) #(和)必须被转义,以避免参数解析中的不正确分词
- bash: syntax error near unexpected token `('
- $ ([ "s" \> "l" -a \( "l" \> "a" -o "l" \> "p" \) ]&&echo yes)
- yes
- $ ([[ "s" > "l" && ( "l" > "a" || "l" > "p" ) ]]&&echo yes; ) #而表达式则不需要考虑这个
- yes
复制代码 |
|