diff --git a/src/node.cc b/src/node.cc index cb5b25bcc9..107816ed44 100644 --- a/src/node.cc +++ b/src/node.cc @@ -2389,13 +2389,31 @@ static void ParseArgs(int argc, char **argv) { strcmp(arg, "--print") == 0 || strcmp(arg, "-pe") == 0 || strcmp(arg, "-p") == 0) { - if (argc <= i + 1) { + bool is_eval = strchr(arg, 'e') != NULL; + bool is_print = strchr(arg, 'p') != NULL; + + // argument to -p and --print is optional + if (is_eval == true && i + 1 >= argc) { fprintf(stderr, "Error: %s requires an argument\n", arg); exit(1); } - print_eval = print_eval || strchr(arg, 'p') != NULL; + + print_eval = print_eval || is_print; argv[i] = const_cast(""); + + // --eval, -e and -pe always require an argument + if (is_eval == true) { + eval_string = argv[++i]; + continue; + } + + // next arg is the expression to evaluate unless it starts with: + // - a dash, then it's another switch + // - "\\-", then it's an escaped expression, drop the backslash + if (argv[i + 1] == NULL) continue; + if (argv[i + 1][0] == '-') continue; eval_string = argv[++i]; + if (strncmp(eval_string, "\\-", 2) == 0) ++eval_string; } else if (strcmp(arg, "--interactive") == 0 || strcmp(arg, "-i") == 0) { force_repl = true; argv[i] = const_cast(""); diff --git a/test/simple/test-cli-eval.js b/test/simple/test-cli-eval.js index 236c990491..eb619e1d50 100644 --- a/test/simple/test-cli-eval.js +++ b/test/simple/test-cli-eval.js @@ -48,7 +48,7 @@ child.exec(nodejs + ' --eval "console.error(42)"', }); // assert that the expected output is written to stdout -'--print -pe -p'.split(' ').forEach(function(s) { +['--print', '-p -e', '-pe', '-p'].forEach(function(s) { var cmd = nodejs + ' ' + s + ' '; child.exec(cmd + '42', @@ -79,3 +79,9 @@ child.exec(nodejs + ' -e ""', function(status, stdout, stderr) { assert.equal(stdout, ''); assert.equal(stderr, ''); }); + +// "\\-42" should be interpreted as an escaped expression, not a switch +child.exec(nodejs + ' -p "\\-42"', + function(err, stdout, stderr) { + assert.equal(stdout, '-42\n'); + });