繁体   English   中英

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

[英]passing quoted arguments to node via shell script?

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

评估 [ arg ...]

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM