Monday, 29 October 2018

bash - Need to expand a variable in a HEREDOC that is in quotes


Is it possible to use a HEREDOC and get variable expansion to happen when the variable is in quotes?


Example: $package is an environment variable that is set before the script runs


#!/bin/bash

cat > out.json <<'EOF'
{
"apps": [
{
"cwd":"/usr/local/$package"
}
}
EOF

Expected output if $package="www"


{
"apps": [
{
"cwd":"/usr/local/www"
}
}

Answer



TL;DR


Use < instead of <<'EOF'.




This is what POSIX says about here-documents [emphasis mine]:



[n]<    here-document
delimiter

[…]


If any part of word is quoted, the delimiter shall be formed by performing quote removal on word, and the here-document lines shall not be expanded. Otherwise, the delimiter shall be the word itself.


If no part of word is quoted, all lines of the here-document shall be expanded for parameter expansion, command substitution, and arithmetic expansion. […]



In you case word is 'EOF' (quoted!), so $package inside the here-document is not expanded. Drop these quotes and you will get the desired result.


cat > out.json <{
"apps": [
{
"cwd":"/usr/local/$package"
}
}
EOF

Note this has nothing to do with quotes that surround the variable inside the here-document.


No comments:

Post a Comment

Where does Skype save my contact&#39;s avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...