简体   繁体   English

通过变量传递命令行参数

[英]Passing command line parameters through variables

I'm trying to construct a command line by adding parameters with information from the "outside world" (namely, user input). 我试图通过添加带有来自“外部世界”(即用户输入)的信息的参数来构造命令行。

Say that I want to grep a file for a set of words that the user gives me (it is just to show you the use case, I'm really trying to run a bioinformatics code, but everybody have grep for testing purposes). 假设我要为用户提供的一组单词grep文件(这只是为了向您展示用例,我实际上是在尝试运行生物信息学代码,但是每个人都有grep用于测试)。 The idea is that I will have a list of words in a bash array: 我的想法是在bash数组中有一个单词列表:

$ L=("foo" "bar")

And I want to use that list to end up with a line equivalent to 我想使用该列表以等于

$ grep -e foo -e bar input.txt

I used an approach of generating the needes parameter string with 我使用了一种生成needes参数字符串的方法

$ P=${L[@]/#/-e }

$ echo "$P"
-e foo -e bar

But I cannot use it as is (assuming a file that contains foo and bar): 但是我不能按原样使用它(假定包含foo和bar的文件):

$ grep "$P" input.txt
<No output>

Last command, actually searched for the string "-e foo -e bar". 最后一条命令,实际上是搜索字符串“ -e foo -e bar”。

If I run that command without the quotes, it works, but the it also triggers the SC2086 warning in shellcheck.net, which I'm trying to avoid. 如果我运行该命令时不带引号,则它可以工作,但它还会在shellcheck.net中触发SC2086警告,我正尝试避免该警告。

I already tried several combinations of arrays, parenthesis, quotes... but I'm unable to nail the exact syntax for my needs. 我已经尝试了数组,括号,引号的几种组合...但是我无法根据我的需要确定确切的语法。 Anyone have that syntax? 有人有这种语法吗?

If you quote the argument string, it will be interpreted as one long argument. 如果您引用参数字符串,它将被解释为一个长参数。 If you don't quote it, then you rely on word-splitting which has many caveats and is not recommended. 如果不引用它,那么您将依靠分词,这有很多警告,不建议这样做。

You could build the arguments like this: 您可以像这样构建参数:

arg=()
arr=(foo bar)
for a in "${arr[@]}"; do arg+=(-e "$a"); done

grep "${arg[@]}" input

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

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