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:
variable1variable2variable3[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_1variable_2variable_3[and so on]
It would be great if you could simply do the following:
1 | #!/bin/bash |
2 | |
3 | for suffix in {1..3}; do |
4 | variable$suffix=foobar |
5 | done |
But you'll get an error:
1 | $ bash myordinalsuffixes.sh |
2 | myordinalsuffixes.sh: line 4: variable1=foobar: command not found |
3 | myordinalsuffixes.sh: line 4: variable2=foobar: command not found |
4 | myordinalsuffixes.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 | |
3 | while :; do |
4 | ((count++)) |
5 | read |
6 | [ $REPLY ] || break |
7 | read<<<$REPLY item$count |
8 | done |
9 | |
10 | count=0 |
11 | while :; do |
12 | ((count++)) |
13 | read<<<item$count item |
14 | [ -z ${!item} ] && break || echo $item=${!item} |
15 | done |