나는 모든 호스트 이름에 대한 전역 변수를 만드는 것을 좋아합니다. 부분적으로 작동하려면 변수 이름 ip_ = ipadres를 가져와야 했습니다...
완료 루프 동안 변수가 손실되었습니다.
#!/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