简体   繁体   中英

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). The idea is that I will have a list of words in a bash array:

$ 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

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

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

But I cannot use it as is (assuming a file that contains foo and bar):

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

Last command, actually searched for the string "-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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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