2

How to pass the variable value in echo statement?

testvar="actualvalue"
echo 'testing "${testvar}", "testing", "testing" ;'

Expected output:

testing "actualvalue", "testing", "testing" ;

But, I am getting the below output:

testing "${testvar}", "testing", "testing" ;

Can someone help me with this?

Dev
  • 123
  • 1
  • 5
  • 3
    The single quotes in the `echo` command remove the special meaning of $. Replace the single quotes with double quotes, and put backslashes before the other double quotes: `echo "testing \"${testvar}\", \"testing\", \"testing\" ;"`. – berndbausch Feb 24 '21 at 07:41
  • 2
    ... see for example [What is the difference between “…”, '…', $'…', and $“…” quotes?](https://unix.stackexchange.com/a/503014/65304) – steeldriver Feb 24 '21 at 07:46

1 Answers1

4

Remove the single quotes:

$ testvar="actualvalue"
$ echo testing "${testvar}", "testing", "testing" ;
testing actualvalue, testing, testing

The single-quote inhibits variable expansion.

Without double-quotes gives you the same output:

$ echo testing ${testvar}, testing, testing ;
testing actualvalue, testing, testing

But if you really want double-quotes in the output, escape them:

$ echo "testing \"${testvar}\", \"testing\", \"testing\" ;"
testing "actualvalue", "testing", "testing" ;
GAD3R
  • 63,407
  • 31
  • 131
  • 192
Stewart
  • 12,628
  • 1
  • 37
  • 80
  • 1
    `${testvar}` outside double quotes is invoking the split+glob operator, so it would only give the same output in the special cases where `${testvar}` contains no wildcard characters nor characters of `$IFS`. Also note that `echo` can generally not be used to output arbitrary data. [You'd use `printf` for that instead](/q/65803). – Stéphane Chazelas Feb 24 '21 at 10:14