脚本test.sh:
#!/bin/bash
if [[ $# -eq 0 ]]; then
echo "no arg"
else
echo "have arg"
fi
当我把它作为
运行时./test.sh
它说“没有arg”,这是预期的,但如果我以
运行它sh ./test.sh
它打印“有arg”,但是你打印$#,在两种情况下都是零。
但是,下面的脚本
#!/bin/bash
if [ $# -eq 0 ]; then
echo "no arg"
else
echo "have arg"
fi
在两种情况下都打印“no arg”。
有人可以解释一下吗?为什么[[ ... ]]
与$#
不同地解释[ ... ]
?
我读到的关于[[ ... ]]
的解释对此并不十分清楚。
答案 0 :(得分:2)
/ bin / sh通常是与bash不同的shell解释器。在我的ubuntu系统上,它是一个破折号的符号链接。不同的shell有不同的语法。
[ foo ]
和test foo
在bash和dash中都是等效的。
[[ foo ]]
是一个类似于[ ]
测试的bash表达式,但在man bash
中有一些差异。
Dash没有[[
命令,导致错误 - exitcode,以及else分支的执行。
[[ expression ]]
Return a status of 0 or 1 depending on the evaluation of the
conditional expression expression. Expressions are composed of
the primaries described below under CONDITIONAL EXPRESSIONS.
Word splitting and pathname expansion are not performed on the
words between the [[ and ]]; tilde expansion, parameter and
variable expansion, arithmetic expansion, command substitution,
process substitution, and quote removal are performed. Condi‐
tional operators such as -f must be unquoted to be recognized as
primaries.
When the == and != operators are used, the string to the right
of the operator is considered a pattern and matched according to
the rules described below under Pattern Matching. If the shell
option nocasematch is enabled, the match is performed without
regard to the case of alphabetic characters. The return value
is 0 if the string matches (==) or does not match (!=) the pat‐
tern, and 1 otherwise. Any part of the pattern may be quoted to
force it to be matched as a string.
An additional binary operator, =~, is available, with the same
precedence as == and !=. When it is used, the string to the
right of the operator is considered an extended regular expres‐
sion and matched accordingly (as in regex(3)). The return value
is 0 if the string matches the pattern, and 1 otherwise. If the
regular expression is syntactically incorrect, the conditional
expression's return value is 2. If the shell option nocasematch
is enabled, the match is performed without regard to the case of
alphabetic characters. Any part of the pattern may be quoted to
force it to be matched as a string. Substrings matched by
parenthesized subexpressions within the regular expression are
saved in the array variable BASH_REMATCH. The element of
BASH_REMATCH with index 0 is the portion of the string matching
the entire regular expression. The element of BASH_REMATCH with
index n is the portion of the string matching the nth parenthe‐
sized subexpression.
答案 1 :(得分:1)
在我的情况下(ubuntu 9.04)我还看到以下错误行超过“have arg”行:
./ test.sh:6: [[:not found
确实应该如此; / bin / sh是'dash'的符号链接,而不是'bash'。