Pass a string with spaces as an argument to Bash function

Tag: bash Author: onepiecewjd Date: 2010-10-11

Given the following string variable

VAR="foo         bar"

I need it to be passed to a bash function, and accesses it, as usual, via $1. So far I haven't been able to figure out how to do it:

function testfn(){
    echo "in function: $1"
VAR="foo         bar"
echo "desired output is:"
echo "$(testfn 'foo           bar')"
echo "Now, what about a version with \$VAR?"
echo "Note, by the way, that the following doesn't do the right thing:"
echo $(testfn "foo           bar") #prints: "in function: foo bar"

Best Answer

Bash is smart and pairs of double quotes match either inside or outside of a $( ... ) structure.

Hence, echo "$(testfn "foo bar")" is valid, and the result of your testfn function will only be considered as a single argument to the echo internal command.


Right on. I was assuming that nested double quotes shouldn't be used, ever. However, echo "(testfn "$VAR")" works just fine.