2

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:

#!/bin/bash
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"

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.