通过shell脚本将引用的parameter passing给节点?
我有一个文本文件,每行是我想传递给nodejs脚本的参数列表。 以下是一个示例文件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 script.js "This is the first argument" "This is the second argument" [ 'This is the first argument', 'This is the second argument' ]
这里发生了什么? 有更多的节点方式来做到这一点?
这里发生的事情是, $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 …]
这些参数被读取并连接成一个命令。 这个命令然后被shell读取和执行,并且它的退出状态作为eval的值被返回。 如果没有参数 ,或者只有null参数,则eval返回0。