0
#!/bin/sh
b=( a b c d )
count=1
for a in ${b[@]}; do
    example_$count=$a  # how do I declare this variable "example_$count"
    echo example_$count; # and how do I echo it
    (( count++ ))
done

What I need is something like this:

$example_1=a 
$example_2=b 
$example_3=c 
$example_4=d
devnull
  • 118,548
  • 33
  • 236
  • 227
tommyhsu
  • 27
  • 6
  • 1
    why do you want to do this? Why not just use the array? For example, `$example_1` would correspond to `${b[0]}`. – dogbane Jul 29 '13 at 07:24

2 Answers2

1

For declaring variables, you use eval. For displaying variables, you have two solutions : eval, or Bash syntax ${!var}.

So your script becomes, with only eval :

#!/bin/bash
b=( a b c d )
count=1
for a in ${b[@]}; do
    var=example_$count
    eval $var=$a
    eval echo \$$var
    (( count++ ))
done

Or with Bash syntax for display :

#!/bin/bash
b=( a b c d )
count=1
for a in ${b[@]}; do
    var=example_$count
    eval $var=$a
    echo ${!var}
    (( count++ ))
done
Mickaël Bucas
  • 683
  • 5
  • 20
0

The most simple solution:

example=( a b c d )

Instead of $example_1, just use ${example[0]}. At first glance, this may not look like what you want. But keep in mind that BASH is a scripting language with a history (= it has many, many quirks). So while it's not exactly what you think you need, it will work as you expect in most cases.

One reason might be that you think that arrays should start with index of 1 (which is a common beginners mistake that causes lots of problems later). But if you insist, you can insert an empty 0 element to simulate the desired behavior:

example=( "" a b c d )

of if you already have the array:

example=( "" "${example[@]}" ) # prepend empty element to existing array
Community
  • 1
  • 1
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820