我在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
只需要一个参数,所以它会出错。
您想要的是 $*
,它连接参数而不创建多个参数:
$ printf "Argument: %s\n" "Hello $* world"
Argument: Hello foo bar baz world
`echo $@`
基本上是一种做同样事情的黑客方法 - 将多个参数连接到一个字符串中 - 除非它会在许多边缘情况下中断,例如嵌入换行或通配符:
$ 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
关于Node.js 语法错误 : Unexpected end of input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23500098/