envyM6
envyM6

Reputation: 1237

Bash variable within single and double quote

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>

Upvotes: 1

Views: 95

Answers (3)

IceCode
IceCode

Reputation: 303

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

Upvotes: 2

anubhava
anubhava

Reputation: 786041

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.

Upvotes: 2

M. Nejat Aydin
M. Nejat Aydin

Reputation: 10133

Alternatively, you can use the builtin command printf:

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

Upvotes: 2

Related Questions