Node.js SyntaxError:意外的input结束
我在shell脚本中写了一个函数:
function nodee() { node -e "console.log((function() { $@ })());" } export -f nodee
并像这样调用它:
nodee "var a = 1, b = 2;" "return a + b;"
然后我得到一个错误:
[eval]:1 console.log((function() { var a = 1, b = 2; SyntaxError: Unexpected end of input at Object.<anonymous> ([eval]-wrapper:6:22) at Module._compile (module.js:456:26) at evalScript (node.js:532:25) at startup (node.js:80:7) at node.js:902:3
但是,这是确定的:
nodee "var a = 1, b = 2; return a + b;"
最后,我发现像这样声明nodee
可以解决这个问题:
function nodee() { node -e "console.log((function() { `echo $@` })());" } export -f nodee
但是下面的两行显示了相同的结果:
echo "console.log((function() { `echo $@` })());" echo "console.log((function() { $@ })());"
那么问题是这两条线有什么区别呢?
node -e "console.log((function() { `echo $@` })());" node -e "console.log((function() { $@ })());"
Mac OS X:10.9.2&Node.js:0.10.26
提前致谢!
$@
是引号中的魔法,并且导致多个参数:
$ set -- foo bar baz $ printf "Argument: %s\n" "Hello $@ world" Argument: Hello foo Argument: bar Argument: baz world
由于node
只需要一个参数,就会跳出来。
你想要的是$*
,它连接参数而不创build多个参数:
$ printf "Argument: %s\n" "Hello $* world" Argument: Hello foo bar baz world
`echo $@`
基本上是一种很简单的方式 – 将多个参数串联成一个string – 除了它会像embedded式换行符或globs一样在一些边界情况下被破坏:
$ set -- "var = 2 * 3;" $ printf "Argument: %s\n" "Hello $* world" Argument: Hello var = 2 * 3; world $ printf "Argument: %s\n" "Hello `echo $@` world" Argument: Hello var = 2 a.class a.java a.out barcode.png [...] 3; world