通过shell脚本将引用的参数传递给节点?

时间:2011-11-20 22:34:49

标签: bash node.js

我有一个文本文件,其中每一行都是我想传递给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' ]

这里发生了什么?有更多的节点方法吗?

1 个答案:

答案 0 :(得分: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.

相关问题