Bash – Create Variables and Assign Values via Loop

bashshellshell-script

Is there a way to create bash variables and assign them values via a loop?

Something along the lines of:

#!/bin/bash

c=0
for file in $( ls ); do
    var"$c"="$file";
    let c=$c+1;
done

EDIT: Thank you to @Costas and @mdpc for pointing out this would be a poor alternative to a list; the question is theoretical only.

Best Answer

Well, you absolutely can using eval as follows:

c=0
for file in $( ls ); do
    eval "var$c=$file";
    c=$((c+1));
done

This code will create variables named var0, var1, var2, ... with each one holding the file name. I assume you will have a good reason you want to do that over using an array ...

Related Question