当bash执行代码时,为什么源代码会出现语法错误?

Nic*_*ick 1 bash shell posix

脚本很简单:

#!/bin/bash
if [[ 0 ]]; then
   echo foo
fi
Run Code Online (Sandbox Code Playgroud)

错误表现为:

$ source ./sample.sh
./sample.sh:2: parse error near `]]'
Run Code Online (Sandbox Code Playgroud)

但请注意,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.
Run Code Online (Sandbox Code Playgroud)

从bash文档:

[[ 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.
Run Code Online (Sandbox Code Playgroud)

请注意,语法错误显示为表达式0"0"表达式.

添加一个运算符(例如-n)可以解决解析错误,但似乎不需要从文档中进行操作,也不能解释为什么bash评估它就好了.

Joh*_*ica 7

你的shell不是bash.当你运行source ./sample.sh它时,在当前shell的上下文中运行脚本,无论是什么,忽略#!/bin/bashhash-bang行.

顺便说一下,if [[ 0 ]]打算做什么?这有点荒谬.[[ 0 ]]相当于[[ -n 0 ]]检查if 0是否为非空字符串.这保证是真的.

要写一个简单的真或假检查,我会写:

if true; then
Run Code Online (Sandbox Code Playgroud)

要么

if false; then
Run Code Online (Sandbox Code Playgroud)