bash quoting function arguments – Pass Arguments to Function Exactly As-Is

argumentsbashfunctionquoting

I have the following function:

bar() { echo $1:$2; }

I am calling this function from another function, foo. foo itself is called as follows:

foo "This is" a test

I want to get the following output:

This is:a

That is, the arguments that bar receives should be the same tokens that I pass into foo.

How does foo need to be implemented in order to achieve this? I’ve tried the following two implementations, but neither works:

  • foo() { bar $*; }

    – output: this:is

  • foo() { bar "$*"; }

    – output: this is a test:

My question is effectively how I can preserve the quoting of arguments. Is this possible at all?

Best Answer

Use "$@":

$ bar() { echo "$1:$2"; }
$ foo() { bar "$@"; }
$ foo "This is" a test
This is:a

"$@" and "$*" have special meanings:

  • "$@" expands to multiple words without performing expansions for the words (like "$1" "$2" ...).
  • "$*" joins positional parameters with the first character in IFS (or space if IFS is unset or nothing if IFS is empty).
Related Question