[英]Nodejs process.argv[2] is omitting data after space even with \ when run through bash script
So I have a node script that takes an argument, if I run the node script alone then something like game\\ of\\ thrones
the entire string is considered process.argv[2]
which is what I wanted and expected, the problem is when I run a very small bash script called add
which consists of 因此,我有一个带参数的节点脚本,如果我单独运行该节点脚本,则像
game\\ of\\ thrones
这样的东西将整个字符串视为process.argv[2]
,这是我想要和期望的,问题是当我运行一个名为add
的非常小的bash脚本,其中包括
#!/bin/bash
echo `nodejs ~/Codes/localHost/node/headsUp/add.js $1`
and then run ./add game\\ of\\ thrones
now process.argv[2]
is only game
why is this? 然后运行
./add game\\ of\\ thrones
process.argv[2]
只是game
,这为什么? if at all possible I would love to have a solution that allows me to put spaces between arguments to have multiple arguments rather than use something like $@
. 如果有可能,我希望有一个解决方案,允许我在参数之间放置空格以具有多个参数,而不是使用
$@
。 Thanks in advance. 提前致谢。 Oh and when I
echo $1
in the bash script it does come up as the full game of thrones
. 哦,当我在bash脚本中
echo $1
,它的确是完整game of thrones
。
When you fail to quote $1
, you are telling bash to resplit the parameter into words. 当您无法引用
$1
,您就是在告诉bash将参数重新分割成单词。 In order to pass $1
(or any other parameter or variable) verbatim into another script or binary, you need to make sure it is quoted: 为了逐字传递
$1
(或任何其他参数或变量)到另一个脚本或二进制文件中,您需要确保将其引用:
echo `nodejs ~/Codes/localHost/node/headsUp/add.js "$1"`
Note that the output from nodejs
will also be word-split, since it is not quoted. 请注意,由于未引用
nodejs
的输出, nodejs
也会将其拆分。 If you wanted to preserve formatting (such as newlines), you would need to quote that as well: 如果要保留格式(例如换行符),则还需要引用该格式:
echo "$(nodejs ~/Codes/localHost/node/headsUp/add.js "$1")"
Here I changed the deprecated backtick syntax into the recommended $(...)
syntax, which nests better. 在这里,我将不推荐使用的反引号语法更改为推荐的
$(...)
语法,这样可以更好地嵌套。
It feels very 'workaroundish' which makes me feel like there is a better way but for those who may need to have this working you can concatenate your process.argv
variable. 感觉很“变通”,这让我觉得有一种更好的方法,但是对于那些可能需要进行此工作的人,您可以将其
process.argv
变量连接起来。 using this method you can run your script and give it multiple arguments separated by spaces (actual spaces not spaces prefaced with \\
) 使用此方法,您可以运行脚本并为它提供多个由空格分隔的参数(实际空格不是以
\\
开头的空格)
function conCatArgs(input){
var args = [];
for(i = 0; process.argv.length - 2 > i; i++){
args[i] = input[i + 2]
}
console.log(args);
}
conCatArgs(process.argv);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.