3

I have a Bash script which passes patterns and switches to grep.

#!/bin/bash

foo() {
    grep $@ *.txt
}

foo $@

And, of course, myscript SomeText works but myscript "Text1 Text2" does not. Is there a way to keep the quotes when passing arguments from script to foo() and then from foo() to grep?

Note, that I cannot simply use eval and wrap the whole $@ before grep since it can also contain switches so I need to keep the original quoting as passed from the command line.

Thanks.

2 Answers 2

2

Your grep command looks incomplete, have you script like this with quoted parameters:

#!/bin/bash
set -x # for debug purpose only, comment out later

foo() {
    grep "$@" *.txt
}

foo "$@"

And call it like this:

./myscript "Text1 Text2"
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I thought I already tested your solution but I probably forgot to quote $@ in one of the calls.
@jackhab, the difference between quoted and unquoted is illustrated at stackoverflow.com/a/12316565/7552
2

Simply quote the $@:

#!/bin/bash 

foo() { 
    grep "$@" 
} 

foo "$@" 

This is a difference between $@ and $*.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.