[SITE UNDER CONSTRUCTION AND TESTING.]

BASH-Generated Variable Names that Have Ordinal Suffixes

They Said it Couldn't Be Done without Having Underscores. I Proved Them WRONG!

PLEASE NOTE:

My explanation of the code in this article is unfinished; it is, thus currently missing.

Have you ever wished there were some BASH code construction that would generate variable names that have numbers at the end (ie: ordinal suffixes)? Such as:

variable1
variable2
variable3
[and so on]

Having wanted such a facility myself, I scoured the Web, including coding forums, but the closest anyone's 'solution' came to what I, and others, wanted to do created variable names, each with a number at the end BUT an underscore between the number and the preceeding part of the name, as in (example):

variable_1
variable_2
variable_3
[and so on]

It would be great if you could simply do the following:

1#!/bin/bash
2
3for suffix in {1..3}; do
4  variable$suffix=foobar
5done

But you'll get an error:

1$ bash myordinalsuffixes.sh
2myordinalsuffixes.sh: line 4: variable1=foobar: command not found
3myordinalsuffixes.sh: line 4: variable2=foobar: command not found
4myordinalsuffixes.sh: line 4: variable3=foobar: command not found

My solution? Use a 'here string'. Here's my example script that demonstrates BASH generating ordinally-suffixed variable names (first block of code) and then outputting those names together with their associated values (second block of code). The 'here' construct is the '<<<':

1#!/bin/bash
2
3while :; do
4  ((count++))
5  read
6  [ $REPLY ] || break
7  read<<<$REPLY item$count
8done
9
10count=0
11while :; do
12  ((count++))
13  read<<<item$count item
14  [ -z ${!item} ] && break || echo $item=${!item}
15done