开发者

Pass a string with spaces as an argument to Bash function

开发者 https://www.devze.com 2023-01-21 09:00 出处:网络
Given the following string variable VAR=\"foobar\" 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:

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         ba开发者_开发问答r"
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"


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消