ksh 坏[… ] 语法不会导致错误
我刚刚在 ksh 脚本中找到了以下代码:
if [ "${file_id}" = "0" ] || [ "${file_id}" = "100" ] || "${file_id}" = "100" ]
then
# Do some stuff
fi
请特别注意,第三个 ${file_id}
之前缺少 [
。
我很高兴这不是一个非常令人愉快的语法,即使没有这个错误,而且在 ksh 中 [[ … ]]
通常比 [ … ]
更可取。
然而,这段代码完全按照预期运行,并且 ksh -n
根本不反对上述内容。为什么上面的方法没有失败呢?
I've just found the following code in a ksh script:
if [ "${file_id}" = "0" ] || [ "${file_id}" = "100" ] || "${file_id}" = "100" ]
then
# Do some stuff
fi
Note, in particular, the missing [
before the third ${file_id}
.
I'm happy that this isn't very pleasant syntax, even without that error, and that [[ … ]]
is generally preferable to [ … ]
in ksh.
However, this code runs entirely as desired, and ksh -n
doesn't object to the above at all. Why doesn't the above fail?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
if [ "${file_id}" = "0" ] || [“${file_id}”=“100”]|| "${file_id}" = "100" ]
该命令从左到右执行。如果此命令发现
file_id
的值为0
那么它将不会检查下一个条件,因为这些条件是用or
运算符分隔的。如果第一个和第二个条件都不满足,那么它将尝试检查第三个条件,但会失败。if [ "${file_id}" = "0" ] || [ "${file_id}" = "100" ] || "${file_id}" = "100" ]
This command exicuted from Left to Right. If this command found the value of
file_id
is0
then it will not check for the next conditions because, these conditions are separated with theor
operator. If both 1st and 2nd conditions will not satisfied then it will try to check for the 3rd condition and it will be failed.我的第一个猜测是,只要第一个表达式的计算结果为 true,大多数(或所有)Bourne-type shell 都会正确执行。这是预期的行为,因为
&&
和||
实际上使执行短路:即在a || 中b
,如果 a 为真,则不计算 b 部分。考虑以下内容:
还有更多,您不能在短路表达式的右侧输入您想要的任何内容,因为解析器将在执行之前尝试解析整行(即放错位置的元字符 em> 将导致错误)
还要注意,只要命令(内置或外部)执行被推迟,
shell 无法知道它是否有效。相反,shell 保留字语法和元字符的位置在解析时是已知的:
My first guess is that this will execute correctly with most (or all) Bourne-type shells as long as the first expression evaluates true. This is expected behavior, as the
&&
and||
actually short-circuit the execution: i.e. Ina || b
, the b part is not evaluated if a is true.Consider the following:
There is more though, you cannot type whatever you want on the right side of the short-circuiting expression, because the parser will try to parse the entire line, before executing it (i.e. a misplaced metacharacter will cause an error)
Notice also that as long as the command (builtin or external) execution is deferred,
the shell couldn't know if it's valid or not. On the contrary, the shell reserved words syntax and the positions of the metacharacters are known in parse-time: