0

I like to make global variables for all my host names. The must get an variable name ip_ = ipadress I got it working partially...

The variable is lost out of the while done loop

#!/bin/bash

#file x.x

like to make global variables for all hostnames with ip_ in front of it...

#192.168.20.48 dockerhub #192.168.20.48 mysqlserver #192.168.20.48 mqttserver #192.168.20.48 proxyserver #192.168.20.48 domserver #192.168.20.48 dockerserver

tr -d '\r' < /home/pi/iotmenu/testscripts/x.x | while read kola kolb; do if [[ $kola =~ ^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$ ]]; then echo "1 $kolb $kola" eval ip_$kolb=$kola

echo &quot;2 ip_$kolb=$kola&quot; 
    declare &quot;ip_$kolb=$kola&quot;
export &quot;ip_${kolb}=${kola}&quot;
echo &quot;example_in ip_mysqlserver=$ip_mysqlserver&quot;

fi

done

echo "example_out ip_mysqlserver=$ip_mysqlserver"

the variable is lost after the loop

Peregrino69
  • 2,417
pvk
  • 5
  • Don't use variable indirection for this. Use an array, that's what they're for. Use an indexed array if $kolb is an integer, otherwise use an associative array. In this case, you'll need an associative array. e.g. (before the loop): declare -Ax ip (-A for associative array, -x to export the array - see help declare in bash). Later, in the loop: ip[$kolb]="$kola". – cas Mar 19 '23 at 01:38

2 Answers2

0

Take care of double quotes.

# incorrect
export "ip_${kolb}=${kola}"

correct, as long as $kolb follows rules of env variables

export ip_${kolb}="${kola}"

White Owl
  • 5,129
0
#!/bin/bash

# like to make global variables for all hostnames with ip_ in front of it...
# file x.x
#192.168.20.48   dockerhub
#192.168.20.48   mysqlserver
#192.168.20.48   mqttserver
#192.168.20.48   proxyserver
#192.168.20.48   domserver
#192.168.20.48   dockerserver

get_ip(){
tr -d '\r' < /home/pi/iotmenu/testscripts/x.x | 
while read kola kolb; do
    if [[ $kola =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        echo "1 $kolb $kola"
        eval "ip_$kolb"="$kola"

        echo "2 ip_$kolb=$kola" 
            declare ip_$kolb=$kola
        export ip_${kolb}="${kola}"

        echo "3 example_in ip_mysqlserver=$ip_mysqlserver"
    fi
done
}

get_ip

echo "4 example_out ip_mysqlserver=$ip_mysqlserver"
# the variable is lost after the loop
Peregrino69
  • 2,417
pvk
  • 5
  • Please have a look at how to write a good answer. When writing next question / answer, please also click on the question mark on the top right hand corner of the top bar. That'll show you the available formatting options. Using those correctly helps to keep the question/answer readable. – Peregrino69 Mar 18 '23 at 16:29
  • Is this an answer or a repeat of the question? – ilkkachu Mar 18 '23 at 16:30
  • This is a repeat of the question with corrections based on the thirst answer... But still not working... I have the variables filled within the loop but after the execution of function , the value is gone – pvk Mar 18 '23 at 21:41