脚本中的 while-done 循环结束后变量内容丢失

脚本中的 while-done 循环结束后变量内容丢失

我喜欢为所有主机名创建全局变量。必须得到一个变量名 ip_ = ipadress 我让它部分工作......

变量在 while done 循环中丢失

#!/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 "2 ip_$kolb=$kola" 
        declare "ip_$kolb=$kola"
    export "ip_${kolb}=${kola}"
    echo "example_in ip_mysqlserver=$ip_mysqlserver"

    fi
done

echo "example_out ip_mysqlserver=$ip_mysqlserver"
# the variable is lost after the loop

答案1

注意双引号。

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

# correct, as long as $kolb follows rules of env variables
export ip_${kolb}="${kola}"

答案2

#!/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

相关内容