2

I have an array in which every element may contain another variable. The array assignment is from a file as follows:

FILE_CLEANUP_DIR_ARR=($(cat cleanup.list | sed '/^[[:blank:]]*$/d' | sed '/^[#]/d'))

How can I restore the aray with the expanded variables.

TARGET_DIR=/SOMEROOTDIR

FILE_CLEANUP_DIR_ARR[0] has value literally as $TARGET_DIR/SOMESUBDIR0

FILE_CLEANUP_DIR_ARR[1] has value literally as $TARGET_DIR/SOMESUBDIR1

How can I restore this FILE_CLEANUP_DIR_ARR to expanded variables as follows.

FILE_CLEANUP_DIR_ARR[0] = /SOMEROOTDIR/SOMESUBDIR0

FILE_CLEANUP_DIR_ARR[1] = /SOMEROOTDIR/SOMESUBDIR1

Sample code. Not working.

i=0
for CDIR in "${FILE_CLEANUP_DIR_ARR[@]}";
do
FILE_CLEANUP_DIR_ARR[i]="$CDIR"
((i++))
done
pLumo
  • 22,565
  • 2
    Is there a reason why you have shell code in the array's elements instead of expanded strings? It seems the easiest way to solve this would be to expand the values at the time of assigning them to the array from the start. – Kusalananda Aug 22 '19 at 14:21
  • I am actually reading this array by taking entries from a flat file, that has the literal values as $TARGET_DIR and the assignment is as follows FILE_CLEANUP_DIR_ARR=($(cat cleanup.list | sed '/^[[:blank:]]*$/d' | sed '/^[#]/d')) – Srinivasarao Kotipatruni Aug 22 '19 at 14:23
  • I added that useful information to the question ;-) – pLumo Aug 22 '19 at 14:41

1 Answers1

5

Expand the variables when reading the input using envsubst:

export TARGET_DIR=/some/path/
FILE_CLEANUP_DIR_ARR=($(awk '!/^ *#/ && NF' global_file_transfer_cleanup.list | envsubst))

(awk part via.)


Bad alternative for this would be using eval:

FILE_CLEANUP_DIR_ARR[i]=$(eval printf '%s' "$CDIR")
pLumo
  • 22,565