9

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.

  • 1
    NOTE: Be aware that your setup will change/modify/assign variables only in the current process and NOT the parent process if you execute this as a command. You could source the file using the '.' command (EX: . new_vars) to make this happen within the current process. – mdpc Apr 18 '15 at 20:29
  • Ok, but the above doesn't work actually run; var"$c" breaks it. @Costas 's answer demonstrates how to assign multiple values to a single list variable - I'm just asking theoretically whether variables can actually be generated with a loop. – py4on Apr 18 '15 at 20:34
  • Hmmm...why so complicated, just using a new variable creates it without any fanfare. – mdpc Apr 18 '15 at 20:36
11

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 ...

5

Possible you mean array. There are some ways to assign values

First:

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

Second:

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

Third:

for file in $( ls ); do
    var[${#var}]="$file";
done

Fourth:

var=( $(ls) )

Fifth

...

  1. there is no need to use ls , just put * for all files
  2. inside [] the $ sign can be ommited
  • Thank you; my question is potentially more theoretical than actually practical. However, when I echo $var with the commands you list above I only get the first file 'listed' by ls. Am I doing something wrong? – py4on Apr 18 '15 at 20:19
  • 1
    If you wants to output all array you have to use echo ${var[*]} (or ${var[@]}), single element can be called like echo ${var[1]}. Note: $var is equal ${var[0]} – Costas Apr 18 '15 at 20:25
  • 1
    @py4on Other way is use a loop: for v in "${var[@]}";do echo $v;done – Costas Apr 18 '15 at 20:29

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.