Search code examples
bashvariablesstring-interpolationheredoc

bash script - use and expand variable in cat


In my bash script I have this:

myapphome=/home/username/Documents/myapp

cat << 'EOT' > "$myapphome"/some.properties
dir.root="$myapphome"/app_data
EOT

Expected in some.properties:

dir.root=/home/username/Documents/myapp/app_data

But in actual it is:

dir.root="$myapphome"/app_data

What I am doing wrong here? I mean I want to expand the $myapphome in my some.properties file.


Solution

  • If you want bash to expand variables in a here document, don't quote the terminator:

    cat << EOT > "$myapphome"/some.properties
    dir.root=$myapphome/app_data
    EOT
    

    Also, remove the double quotes from the here document, they won't be removed by the expansion.

    See man bash:

    If EOT is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence \<newline> is ignored, and \ must be used to quote the characters \, $, and `.