FrViPofm
FrViPofm

Reputation: 353

Bash : why variables are not read in the HEREDOC?

I have the file launcher

#! /bin/bash
. ./lib/utils

_name="microapplication-launcher"
_version="0.1"
_shortname="launcher"

DEFAULTS=$(cat <<'EOD'
# openning-prefs : terminal browser folder
launcher-openning-prefs=TRUE|FALSE|TRUE|
EOD
)
CONFIG="$( makeconfig )"

And the file ./lib/utils

__name="microapplication"
#export __name
__version="0.1"
#export __version

CONFIGDIR=~/.config/$__name
CONFIG=""
APPPATH="$HOME/Site/local"
export APPPATH

function makeconfig {
    # global config
    CONFIG="$CONFIGDIR/$__name.conf";


    [ ! -d $CONFIGDIR ] && mkdir $CONFIGDIR

    [ ! -f $CONFIG ] && cat <<"EOD" > $CONFIG
# $__name $__version
app-path=$APPPATH

EOD
}

When runing, it produce ~/.config/microapplication/microapplication.conf with

# $__name $__version
app-path=$APPPATH

The function is run in the launcher. The var __name ( 2 underscores) is well read in makeconfig for making the name of the file, but is no more read in the heredoc to produce the comment. Removing or not the underscores, exporting or not the vars seem having no effect.

Upvotes: 1

Views: 238

Answers (2)

FrViPofm
FrViPofm

Reputation: 353

So I have written a little test script :

#! /bin/bash

mytest="This is my test value"

var0=$(cat <<EOD
No quote: $mytest
EOD
)
var1=$(cat <<'EOD'
Single quote: $mytest
EOD
)
var2=$(cat <<"EOD"
Double quote: $mytest
EOD
)
echo 1- not quoted vairable: $mytest
echo 2- single quoted variable: '$mytest'
echo 3- double quoted variable: "$mytest"
echo 4- "not quoted heredoc: $var0"
echo 5- "single quoted heredoc: $var1"
echo 6- "double quoted heredoc: $var2"

The script returns :

1- not quoted vairable: This is my test value
2- single quoted variable: $mytest
3- double quoted variable: This is my test value
4- not quoted heredoc: No quote: This is my test value
5- single quoted heredoc: Single quote: $mytest
6- double quoted heredoc: Double quote: $mytest

The result shows that

  • double quoted (line 3) strings don't avoid reading internal viariables
  • single (line 5) and double (line 6) quoting heredocs avoid reading the internal variables.

Upvotes: 0

Thilo
Thilo

Reputation: 262474

Variables in a HEREDOC are not expanded if you quote the delimiter.

Change

 cat <<"EOD"

to

 cat <<EOD

Upvotes: 3

Related Questions