脚本非常简单:
#!/bin/bash
if [[ 0 ]]; then
echo foo
fi
错误表现为:
$ source ./sample.sh
./sample.sh:2: parse error near `]]'
但请注意bash
能够很好地执行脚本:
$ /bin/bash ./sample.sh
foo
$ /bin/bash --version
GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
来自bash docs:
[[ 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.
...
CONDITIONAL EXPRESSIONS
Conditional expressions are used by the [[ compound command and the
test and [ builtin commands to test file attributes and perform string
and arithmetic comparisons. Expressions are formed from the following
unary or binary primaries.
...
string
-n string
True if the length of string is non-zero.
请注意,语法错误会以0
或"0"
作为表达式显示。
添加一个运算符(例如-n
)可以解决解析错误,但它似乎不是必须从文档中解释,也不能解释为什么bash
评估它就好了。
答案 0 :(得分:7)
你的shell不是bash。当你运行source ./sample.sh
时,它会在当前shell的上下文中运行脚本,无论是什么,忽略#!/bin/bash
hash-bang行。
顺便问一下,if [[ 0 ]]
打算做什么?这有点荒谬。 [[ 0 ]]
相当于[[ -n 0 ]]
,它会检查0
是否为非空字符串。这保证是真的。
要写一个简单的真或假检查,我会写:
if true; then
或
if false; then