bash script - use and expand variable in cat

Viewed 675

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.

2 Answers

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 `.

Just remove the single quotes from the terminator. The quotes are used when you don't want to expand variables in heredoc:

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

You might wanna remove the double quotes around your variable as well ;)

Related