[和[[有什么不同
时间:2011-01-25
来源:互联网
以下是个人的一些总结,有不同意见欢迎讨论
复制代码
也就是说[处理里面的字串是当作参数来处理的,而[[对待其中的字串是当作表达式来处理的
那么当作参数和表达式有什么不同呢?
表达式中不会有wordsplitting 或者glob expansion,而参数处理会有
复制代码
再来看看glob expansion
复制代码
参数传递中<和>会被解析成重定向符号,所以必须转义掉
复制代码
参数传递中小括号会被分割成token,而在表达式中则会被解析成运算顺序
复制代码
- $ 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
- $ 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
- $ ([ "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
作者: justlooks 发布时间: 2011-01-25
总结的很好。
作者: ly5066113 发布时间: 2011-01-25
收藏了……
作者: yinyuemi 发布时间: 2011-01-25
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28