我有一个文本文件,其中每一行都是我想传递给nodejs脚本的参数列表.这是一个示例文件file.txt:
"This is the first argument" "This is the second argument"
Run Code Online (Sandbox Code Playgroud)
为了演示,节点脚本很简单:
console.log(process.argv.slice(2));
Run Code Online (Sandbox Code Playgroud)
我想为文本文件中的每一行运行此节点脚本,所以我创建了这个bash脚本run.sh:
while read line; do
node script.js $line
done < file.txt
Run Code Online (Sandbox Code Playgroud)
当我运行这个bash脚本时,这就是我得到的:
$ ./run.sh
[ '"This',
'is',
'the',
'first',
'argument"',
'"This',
'is',
'the',
'second',
'argument"' ]
Run Code Online (Sandbox Code Playgroud)
但是,当我直接运行节点脚本时,我得到了预期的输出:
$ node script.js "This is the first argument" "This is the second argument"
[ 'This is the first argument',
'This is the second argument' ]
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?是否有更多节点方法可以做到这一点?
这里发生的事情是,$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
Run Code Online (Sandbox Code Playgroud)
看到所有那些单引号?他们绝对不是你想要的.您可以使用eval正确引用所有内容.这个脚本:
while read line; do
eval node script.js $line
done < file.txt
Run Code Online (Sandbox Code Playgroud)
给我正确的输出:
$ ./run.sh
[ 'This is the first argument', 'This is the second argument' ]
Run Code Online (Sandbox Code Playgroud)
这里也是-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
Run Code Online (Sandbox Code Playgroud)
您可以看到,在这种情况下,在eval步骤之后,引号位于您希望它们所在的位置.下面是对文件eval从bash(1)手册页:
评估 [ arg ...]
的ARGS被读取并连接在一起成一个单一的命令.然后shell读取并执行此命令,并将其退出状态作为eval的值返回.如果没有args或只有null参数,则eval返回0.
| 归档时间: |
|
| 查看次数: |
1624 次 |
| 最近记录: |