bash HERE document evaluation

55 Views Asked by At

I found an odd issue in bash I used HERE-doc as below

source <(cat << EOL | tee /tmp/buildvar_eval.sh
TODAY=$(date +%y%m%d)
PATH_JOB=$HOME
PATH_SRC=${PATH_JOB}/aaaa
PATH_OUT=${PATH_SRC}/bbbb
echo [$PATH_SRC][$PATH_OUT]
EOL
)

What I expected is [/home/myaccount/aaaa][/home/myaccount/bbbb]

but it outpus below.
I executed it same terminal 4 times.

1st try: it print out [][]
2nd try: it print out [aaaa][bbbb]
3rd try: it print out [/home/myaccount/aaaa][/home/myaccount/bbbb]
4th try: it print out [/home/myaccount/aaaa][/home/myaccount/bbbb]

it seems like it does not recusivly evaluate value in HERE-doc

Q1. what's root causing this?
Q2. is there other way to do overcome?

1

There are 1 best solutions below

2
user1934428 On

The first time, you execute the code, the HERE string will be build up. At this time, all variables are initially empty. Your string becomes essentially

PATH_JOB=/home/myaccount
PATH_SRC=/aaaa
PATH_OUT=/bbbb
echo [][]

Then you source this string. This causes PATH_SRC and PATH_OUT to be defined. If you repeat the process, constructing the HERE string now substitutes the newly defined values, and it becomes

PATH_JOB=/home/myaccount
PATH_SRC=/home/myaccount/aaaa
PATH_OUT=/aaaa/bbbb
echo [/aaaa][/bbbb]

You can easier see what's going on, if you separate building the string from sourcing it:

string=$(cat << EOL | tee /tmp/buildvar_eval.sh
TODAY=$(date +%y%m%d)
PATH_JOB=$HOME
PATH_SRC=${PATH_JOB}/aaaa
PATH_OUT=${PATH_SRC}/bbbb
echo [$PATH_SRC][$PATH_OUT]
EOL
)
echo Temorary script:
cat /tmp/buildvar_eval.sh
source  /tmp/buildvar_eval.sh

Now repeat the process and observe how the string gets build up in a different way, because the source command caused the definition of the variables.