1

I wrote a function in shell script:

function nodee() {
    node -e "console.log((function() { $@ })());"
}
export -f nodee

And calling it like this:

nodee "var a = 1, b = 2;" "return a + b;"

Then I got an error:

[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

But this is OK:

nodee "var a = 1, b = 2; return a + b;"

Finally, I found declaring nodee like this can fix the issue:

function nodee() {
    node -e "console.log((function() { `echo $@` })());"
}
export -f nodee

But the following two lines printed the same result:

echo "console.log((function() { `echo $@` })());"
echo "console.log((function() { $@ })());"

So, the question is what's the difference between these two lines?

node -e "console.log((function() { `echo $@` })());"
node -e "console.log((function() { $@ })());"

Mac OS X: 10.9.2 & Node.js: 0.10.26

Thanks in advance!

1 Answer 1

2

$@ is magic in quotes, and results in multiple arguments:

$ set -- foo bar baz
$ printf "Argument: %s\n" "Hello $@ world"
Argument: Hello foo
Argument: bar
Argument: baz world

Since node only expects one argument, it trips up.

What you wanted is $*, which concatenates the parameters without creating multiple arguments:

$ printf "Argument: %s\n" "Hello $* world"
Argument: Hello foo bar baz world

`echo $@` is basically a hacky way of doing the same -- concatening multiple arguments into a single string -- except it'll break in a number of edge cases like with embedded line feeds or 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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.