1

I have a bash script (list.sh) that lists files in a folder and assigns each filename to a bash variable:

#/bin/bash

c=0
for file in *; do
    varr$c="$file";
    c=$((c+1));
done

When I call this from a bash terminal with:

source list.sh

I get:

bash: varr0=07 Get the Balance Right!.mp3: command not found...
bash: varr1=190731_10150450783260347_1948451_n.jpg: command not found...
bash: varr2=199828_10150450907505347_7125763_n.jpg: command not found...
bash: varr3=2022-07-31_19-30.png: command not found...
bash: varr4=2022-08-02_12-06.png: command not found...
bash: varr5=246915_10152020928305567_1284271814_n.jpg: command not found...

I don't know how to put quotes around the file text itself, so that each varr(x) creates itself as a variable in the parent bash script, ie:

varr0="07 Get the Balance Right!.mp3"
Sylv99
  • 151
  • 8
  • 1
    Why are you not using arrays? `var=(*)` seems sooo much easier. – Ole Tange Aug 02 '22 at 14:26
  • `varr$c="$file"` is *not* a variable assignment, because the string to the left of the `=` is not a valid variable name. Since it's not an assignment, the shell treats it as a command. You seem to want `eval varr$c="$file"` which (for c == 0) would evaluate the string `varr0=expanded_value_of_file_without_quotes`....but you really don't want to go down that rabbit hole. – William Pursell Aug 02 '22 at 14:34

3 Answers3

1

Try this script:

c=0
for file in *; do
    printf -v var$((c++)) '%s' "$file"
done
# list variables starting with var and their values
for v in ${!var*}; do
    printf '%s=%s\n' "$v" "${!v}"
done

Though using an array must have been preferred over this method.

M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17
1

It's not a "quote around the text" issue, it's the variable declaration varr$c that's not working. You should be using declare instead.

This script solves your problem :

#/bin/bash

c=0
for file in *; do
    declare varr$c=$file;
    c=$((c+1));
done
bdelphin
  • 76
  • 8
1

You can use the keyword declare as in

$ n=1
$ declare var_$n=20
$ echo $var_1
20

https://www.linuxshelltips.com/declare-command-in-linux/

Something Something
  • 3,999
  • 1
  • 6
  • 21