Home > Back-end >  Bash variable within single and double quote
Bash variable within single and double quote

Time:08-31

Given I have the following env variables declared:

MY_VARIABLE_HERE=myValue
SECOND_VARIABLE=secondValue

How can I retrieve these variable within a single quote, wrapped in double quote. i.e. the following

echo '<tag><action name="$MY_VARIABLE_HERE" value="$SECOND_VARIABLE"/></tag>' > my_text.txt

So the expected output for the my_text.txt would be

<tag>
  <action name="myValue" value="secondValue" />
</tag>

CodePudding user response:

echo '<tag><action name="'"${MY_VARIABLE_HERE}"'" value="'"${SECOND_VARIABLE}"'"/></tag>' > my_text.txt

CodePudding user response:

Alternatively, you can use the builtin command printf:

printf '<tag>\n  <action name="%s" value="%s" />\n</tag>\n' \
       "$MY_VARIABLE_HERE" "$SECOND_VARIABLE"

CodePudding user response:

Without any quoting magic you can use here-doc:

cat <<-EOF
<tag>
   <action name="$MY_VARIABLE_HERE" value="$SECOND_VARIABLE"/>
</tag>
EOF

<tag>
   <action name="myValue" value="secondValue"/>
</tag>

PS: If tab characters are used for indentation then - before EOF is required.

  •  Tags:  
  • bash
  • Related