1

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
  • 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 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 at 14:23
  • I added that useful information to the question ;-) – pLumo Aug 22 at 14:41
4

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")
  • Thank You. The approach with awk is working. I am also checking if I can pipe another sed and replace literal variable. – Srinivasarao Kotipatruni Aug 22 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.