0

I am trying to allocate a bunch of temp files in a loop and export them from within the loop. I then want to loop thru again and echo the values.

for (( i=1; i<=5; i++ ))
do
    dd if=/dev/zero of=/tmp/mh1_$i.out bs=1024 count=1024 status=none
    declare TEMP_FILE_${i}="/tmp/mh1_${i}.out"
    export "TEMP_FILE_${i}"  
done

If I do a echo $TEMP_FILE_1 it correctly prints /tmp/mh1_1.out

But when I try this in a loop it prints 1, 2, 3, 4 and 5.

for (( i=1; i<=5; i++ ))
do
    echo $TEMP_FILE_${i} --> This prints the i value instead of /tmp/mh1_x.out
done

How do I escape the index $i in the echo above to see the real file name ?

SLePort
  • 15,211
  • 3
  • 34
  • 44
ejohnson
  • 139
  • 1
  • 4
  • 16

2 Answers2

3

I suggest using the mktemp utility with arrays:

# create tmp files
tmp_files=()
for ((i=0;i<5;++i)); do
    tmp_files+=("$(mktemp --tmpdir mh1_XXXXXX.out)") || exit 1
done

# process all tmp files
for file in "${tmp_files[@]}"; do
    echo "$file"
    # do something with the file ...
done

# list all tmp files
printf '%s\n' "${tmp_files[@]}"

# list 2nd tmp file
echo "${tmp_files[1]}"

In order to make your code work, you need to use variable indirection and change your second for loop to:

for ((i=1;i<=5;++i)); do
    var=temp_file_$i
    echo "${!var}"
done

Don't use uppercase variables as they could clash with environmental or internal shell variables. Also, note that export is needed only when you want to pass the variables to child processes in the environment.

PesaThe
  • 7,259
  • 1
  • 19
  • 43
  • No need for a loop to print the elements of an array: `printf '%s\n' "${tmp_files[@]}"` – Kusalananda Jun 24 '18 at 09:11
  • @Kusalananda It felt like a reasonable assumption that OP might want to process the files in some way, hence the loop. Good point though! :) – PesaThe Jun 24 '18 at 09:15
1

Why not use bash arrays?

export temp_file
loop
    temp_file[$i]="/tmp/mh1_${i}.out"
    ...
endloop

Then loop over the array

7 Reeds
  • 2,419
  • 3
  • 32
  • 64
  • 4
    As far as I know, you cannot `export` an array. But I don't think OP wants to `export` it anyway. – PesaThe Jun 24 '18 at 07:34
  • I would down check my answer if I could. It is "correct" in that it suggests arrays but "meh" in that I was too tired to think clearly when I wrote it. – 7 Reeds Jun 24 '18 at 15:09