0

i have the following function in a bash script which does not work?

do_get() {
        cmd='<command version="33" cmd="GETINFO" $3</command>'
        echo $cmd
}

Now, if i echo $3 right before the cmd variable it echos out 1234 which i am passing as a 3 argument when executing this. BUT it shows just $3 when i do an echo $cmd.

i tried a couple of things like such below thinking its getting striped out '$3' but it then shows blank '"$3"' same as above

3 Answers 3

2

The variable doesn't expand when inside single quotes. You need to use double quotes instead, but since you have double quotes on the inside, you need to make sure you remember to escape those as well.

do_get() {
        cmd="<command version=\"33\" cmd=\"GETINFO\" $3</command>"
        echo $cmd
}
Sign up to request clarification or add additional context in comments.

5 Comments

I tried the above, still for some reason $3 will not show. IF i echo $3 i see it just fine. I am def. scratching my head on this one.
I Take that Back i was echoing $3 which is my input from the command line and its blank?
Yeah, i am not sure why my argument is lost after the function, BUT if i define a new variable arg3=$3 and echo $arg3 before the cmd= it works fine now. so weird.
@user3100345 $3 refers to the third argument of your function, not the third argument of your script.
@thatotherguy Yes correct thats what i mean. 3rd arg of script. so i had to define it again. weird.
1

Newer versions of bash add a -v flag to the printf command that makes assignments like this a little easier on the eye, in that quoting is reduced.

printf -v cmd '<command version="33" cmd="GETINFO" %d </command' "$3"

Comments

0

The single quote in Bash prevents variable substitution. In order for the third parameter to be substituted, you should enclose your string in double quotes. of course, you have the problem of the double quotes that are part of your string, so they need to be escaped with a backslash:

cmd="<command version=\"33\" cmd=\"GETINFO\" $3 </command>"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.