2011-11-20 132 views
5

我有一个文本文件,其中每行是我想传递给nodejs脚本的参数列表。这里有一个例子文件,file.txt的:通过shell脚本将引用的参数传递给节点?

"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' ] 

这是怎么回事?有更多的节点方式来做到这一点?

回答

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) man pageeval文档:

EVAL [ARG ...]

ARGS被读取并连接在一起成一个单一的命令。然后该命令由shell读取并执行,并且其退出状态返回值为eval。如果没有ARGS,或只有空参数,EVAL返回0

+0

的感谢!那就是诀窍 – Rafael