1

Say I have a function

print_args () {
    for i in $@; do
        echo "$i"
    done
}

When I do

foo='\*'
print_args $foo

I get

\*

(with the backslash) as output.

If I change the definition of foo to foo='*' instead, I get all the files in the current directory when running print_args $foo.

So I either get the backslash included, or the * interpreted, but I don't see how to get the * literally.

The output is the same whether I include double quotes around $foo or not.

Chris Middleton
  • 5,654
  • 5
  • 31
  • 68

1 Answers1

1

The general rule is to quote all variables. It prevents shell expansion and splitting on spaces. So your function should look like this (quoting $@, as well as ${array[@]} splits by arguments):

print_args () {
    for i in "$@"; do
        echo "$i"
    done
}

And call it like this:

print_args "$foo"
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
petersohn
  • 11,292
  • 13
  • 61
  • 98