0

I want to assign the value in the filearray to the variable $filename0,$filename1...etc

how can I set automatically increment filename and assign correct value result should be like this $filename0=filearray[0] $filename1=filearray[1]

Right now, this is my code

filearray=('tmp1.txt' 'tmp2.txt' 'tmp3.txt' 'tmp4.txt' 'tmp5.txt')
let i=0
while (( i <= 4 ));
do
        filename=${filearray[i]}
        i=$(( i+1 ))
done

Sorry for the late update:
now, when there is an extension in the filename it will prompt
"syntax error: invalid arithmetic operator (error token is ".txt")"
but is ok when I echo $(filename1)

count=0
for i in ${filearray[@]};
do
        count=$(( count +1 ))
        declare filename$count=$i
done
y=0
while [ $y < $count ]
do
        y=$(( y + 1 ))
        echo $((filename$y))
done
  • Possible duplicate of [Dynamic variable names in Bash](https://stackoverflow.com/questions/16553089/dynamic-variable-names-in-bash) – kvantour Jul 24 '18 at 07:45

1 Answers1

1

It seems you want to create variable names dynamically. While that is possible* there is almost always a better way to do it, using an associative array for example:

filearray=('tmp1.txt' 'tmp2.txt' 'tmp3.txt' 'tmp4.txt' 'tmp5.txt')

declare -A fileassoc

for ((i=0; i < ${#filearray[@]}; i++))
do
    fileassoc["filename$i"]=${filearray[i]}
done

# To illustrate:
for key in "${!fileassoc[@]}"
do
    echo "$key: ${fileassoc[$key]}"
done

# or
for ((i=0; i < ${#filearray[@]}; i++))
do
    key="filename$i"
    echo "$key: ${fileassoc[$key]}"
done

Gives:

filename4: tmp5.txt
filename1: tmp2.txt
filename0: tmp1.txt
filename3: tmp4.txt
filename2: tmp3.txt

(associative arrays are not ordered, they don't have to be)

*using a dangerous command called eval - there be dragons, don't go there, even with a magic ring

cdarke
  • 42,728
  • 8
  • 80
  • 84
  • that's almost what I need!, is there anyway that I can direct use $((filename$i)) – Jacky Wong Jul 25 '18 at 02:46
  • Yes, but it is insecure, dangerous and bad practice. I would be doing a disservice if I showed you how. What is wrong with the method I show? – cdarke Jul 25 '18 at 06:40