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
1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

that's almost what I need!, is there anyway that I can direct use $((filename$i))
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.