Wednesday, 15 September 2010

bash - How to use a variable in a variable? -



bash - How to use a variable in a variable? -

i editting/extending firewall bash script on ubuntu dedicated server.

the code below excerpt. purpose below reroute/open ips (http, ftp, telnet , ssh) ports for/to 3 boxes.

the problem want utilize variables in variable. --dport ${i}_${j}_port_ext correctly replaced f.i. --dport box0_http_port_ext not seen variable (of course). actually, want should --dport $box0_http_port_ext (mind $ @ beginning)

i tried several things f.i. --dport ${${i}_${j}_port_ext} or --dport $(${i}_${j}_port_ext) not good.

box0_http_port_ext="8080" box0_ftp_port_ext="21" box0_telnet_port_ext="23" box0_ssh_port_ext="22" # allow_box0_http_port_ip="1.2.3.4 99.98.97.96 55.56.57.58" allow_box0_ftp_port_ip="1.2.3.4 55.56.57.58" allow_box0_telnet_port_ip="55.56.57.58" allow_box0_ssh_port_ip="1.2.3.4" # in box0 box1 box2 j in http ftp telnet ssh ips in $allow_${i}_${j}_port_ip $iptables -t nat -a prerouting -p tcp -i $lan_iface -s $ips --dport ${i}_${j}_port_ext -j dnat --to-destination ${i}_ip:${i}_${j}_port_int done done done

please not @ code because excerpt , not complete. question is: how code --dport $box0_http_port_ext making utilize of $i box0 , $j http. keeping in mind $i can box1/box2 , $j can replaced ftp/telnet/ssh.

you can using indirect variable reference (see http://tldp.org/ldp/abs/html/bashver2.html#ex78)

this available in bash version 2 , above, using ! before variable name, within ${ }.

name=${i}_${j}_port_ext echo ${!name}

working example:

#!/bin/bash i=box0 j=http box0_http_port_ext="hello1" box2_telnet_port_ext="hello2" name=${i}_${j}_port_ext echo "varname: $name value: ${!name}" i="box2" j="telnet" name="${i}_${j}_port_ext" echo "varname: $name value: ${!name}"

output:

varname: box0_http_port_ext value: hello1 varname: box2_telnet_port_ext value: hello2

in above illustration $name returns sting box0_http_port_ext, name of initial variable. equivalent ${name}. ! operator evaluates string right side variable name, , returns value stored in variable. ${!name} returns value of ${box0_http_port_ext} hello1.

unfortunately bash not back upwards multi-dimensional arrays, trick can used instead.

the difference other reply $i_$j_port_ext changed ${i}_${j}_port_ext bash knows name of variable ends.

bash shell variables ubuntu

No comments:

Post a Comment