Reputation: 43
I am writing a shell script(bash) that takes multiple arguments and uses the grep command for each of the arguments.
Example: "./script.sh name1 name2 file.txt" the command grep will be called twice "grep name1 file.txt
" and "grep name2 file.txt
".
The problem is when i give multiple options(for example "--color -n"), I concatenate them into a string and passing them to grep like this:
grep "$allParameters" "${arguments[counter]}" "$file"
allParameters: is the string i concat all the options "--color -n"
arguments[counter]: is the current argument that i have to use grep on for example "echo"
file: is the file i want to search
The output is: grep: unrecognized option '--color -n' Usage: grep [OPTION]... PATTERN [FILE]...
Note: For a single option it works fine
Do i have to split the string again? if yes how it is possible to put them all in one line to use the grep command? Is it possible to even do this?
Upvotes: 1
Views: 739
Reputation: 18371
Do not double quote multiple options/flags into as one option. When you quote a string grep
will treat it as single string.
For example:
Valid:
grep -ins --color=auto "foo" inputfile
Valid:
grep "-ins" "--color=auto" "foo" inputfile
Invalid:
grep "-ins --color=auto" "foo" inputfile
Because there is no single option as "-ins --color=auto"
Upvotes: 5