通过shell脚本将带引号的参数传递给node?

5

我有一个文本文件,每一行都是我想传递给Node.js脚本的参数列表。以下是示例文件file.txt:

"This is the first argument" "This is the second argument"

为了演示起见,节点脚本仅为:
console.log(process.argv.slice(2));

我希望能够运行这个节点脚本来处理文本文件中的每一行,因此我制作了这个bash脚本run.sh:

while read line; do
    node script.js $line
done < file.txt

当我运行这个bash脚本时,我得到了以下结果:
$ ./run.sh 
[ '"This',
  'is',
  'the',
  'first',
  'argument"',
  '"This',
  'is',
  'the',
  'second',
  'argument"' ]

但是当我直接运行 Node 脚本时,得到了预期的输出:

$ node script.js "This is the first argument" "This is the second argument"
[ 'This is the first argument',
  'This is the second argument' ]

这是怎么回事?有没有更符合Node.js风格的方法来处理这个问题?
1个回答

9
这里发生的情况是,$line 没有按照你期望的方式发送到程序中。如果在脚本开头添加 -x 标志(例如像 #!/bin/bash -x 这样),你可以看到每一行在执行之前被解释的方式。对于你的脚本,输出如下:
$ ./run.sh 
+ read line
+ node script.js '"This' is the first 'argument"' '"This' is the second 'argument"'
[ '"This',
  'is',
  'the',
  'first',
  'argument"',
  '"This',
  'is',
  'the',
  'second',
  'argument"' ]
+ read line

看到所有的单引号了吗?它们肯定不在你想要它们的位置。您可以使用eval来正确引用所有内容。这个脚本:

while read line; do
    eval node script.js $line
done < file.txt

给我正确的输出:
$ ./run.sh 
[ 'This is the first argument', 'This is the second argument' ]

这里还有带有-x选项的输出,以供比较:
$ ./run.sh 
+ read line
+ eval node script.js '"This' is the first 'argument"' '"This' is the second 'argument"'
++ node script.js 'This is the first argument' 'This is the second argument'
[ 'This is the first argument', 'This is the second argument' ]
+ read line

您可以看到,在这种情况下,在 eval 步骤之后,引号位于您希望它们出现的位置。 这是来自bash(1)手册中关于 eval 的文档:

eval [arg ...]

args 读取并连接成单个命令。 然后shell读取并执行此命令,并将其退出状态作为 eval 的值返回。 如果没有 args 或只有空参数,则 eval 返回0。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接