galactica galactica - 5 months ago 25
Bash Question

Bash: how to pass arguments with special characters like \t

I got a question of how to pass arguments with special characters like

, in Bash.

I know the following to preserve quotes:

function my_grep {
cmd="grep '$@'"
eval $cmd;

so that I can do
my_grep "hello world"

But it seems that I can't preserve \t in this way, e.g.

my_grep "hello\tworld"

Any ideas on how to make this work?


The solution is simple: don't store your command in a variable! See BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail!. Also, don't use eval; it causes all sorts of weird problems. If you skip those (and use "$@" properly), the problem vanishes:

my_grep() {
    grep "$@"

Note that if you call this with my_grep "hello\tworld", it doesn't actually pass in a tab character, it passes a backslash followed by the letter "t" -- which some implementations of grep interpret as matching a tab. If your version of grep doesn't do that, you can pass an actual tab with my_grep $'hello\tworld'.