2

I have a lot of predefined variables in bash script, like

$adr1="address"
$out1="first output"
$adr2="another address"
$out2="second output"

and number is taken from external source, so for example if number is 1 I like to have variable $adr to be value from $adr1 and $out to be from $out1. If number is 2 $adr should be value of $adr2 and $out should be value from $out2 etc.

Edit 27.01.2020: OK, maybe I was not clear enough, will try again with example:

#! /bin/bash

adr1="address"
out1="first-output"
adr2="another-address"
out2="second-output"

if [ $1 -eq 1 ]; then
    adr=$adr1
    out=$out1
elif [ $1 -eq 2 ]; then
    adr=$adr2
    out=$out2
fi

echo "adr=$adr, out=$out"

Now I will run script (lets say it is named test.sh):

./test.sh 1
adr=address, out=first-output

And another run:

./test.sh 2
adr=another-address, out=second-output

I would like to eliminate this if - elif statement because later there will be also adr3 and out3 and adr4 and out4 etc.

Karel H
  • 21
  • 2
  • 1
    Does this answer your question? [Dynamic variable names in Bash](https://stackoverflow.com/questions/16553089/dynamic-variable-names-in-bash) – Titulum Jan 26 '20 at 12:00

2 Answers2

1

you can easily do like key value method, it's completely dynamic !
make a script file and save it, in this case my filename is freeman.sh

#! /bin/bash

for i in $@
do
        case $i in 
           ?*=?*) 
              declare "${i%=*}=${i#*=}" ;;
           *) 
              break

        esac
done
# you can echo your variables like this or use $@ to print all
echo $adr1
echo $out1
echo $adr2
echo $out2

for testing our script we can do like this :

$ bash freeman.sh adr1="address" out1="first-output" adr2="another-address" out2="second-output"

output is :

address
first-output
another-address
second-output
Freeman
  • 9,464
  • 7
  • 35
  • 58
0

I think the construction you need is the following:

#! /bin/bash

adr1="address"
out1="first-output"
adr2="another-address"
out2="second-output"
# and so on...

eval adr='$adr'$1
eval out='$out'$1

echo "adr=$adr, out=$out"
Pierre François
  • 5,850
  • 1
  • 17
  • 38
  • Blanks and new lines inside $adr and $out are correctly handled with this construction. Other possibilities are: `eval adr=\$adr$1` and `eval adr="\$adr$1"` – Pierre François Jan 28 '20 at 08:11