加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash – 如何在变量中使用变量?

发布时间:2020-12-16 01:46:52 所属栏目:安全 来源:网络整理
导读:我在ubuntu专用服务器上编辑/扩展我的防火墙bash脚本. 下面的代码只是一个摘录. 下面的目的是重新路由/打开一些IP我的(http,ftp,telnet和ssh)端口为/ 3箱. 问题是我想在变量中使用变量. 所以–dport ${i} _ ${j} _port_ext被f.i正确替换. –dport box0_http_
我在ubuntu专用服务器上编辑/扩展我的防火墙bash脚本.

下面的代码只是一个摘录.
下面的目的是重新路由/打开一些IP我的(http,ftp,telnet和ssh)端口为/ 3箱.

问题是我想在变量中使用变量.
所以–dport ${i} _ ${j} _port_ext被f.i正确替换. –dport box0_http_port_ext但不被视为变量(当然).实际上,我想要的应该是–dport $box0_http_port_ext(注意开头的$)

我尝试了几件事f.i. –dport ${${i} _ ${j} _port_ext}或–dport $(${i} _ ${j} _port_ext)但这并不好.

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"
#
for i in box0 box1 box2
do
  for j in http ftp telnet ssh
  do   
    for ips in $allow_${i}_${j}_port_ip
    do
      $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

请不要查看代码,因为它是摘录,因此不完整.
问题是:如何编码–dport $box0_http_port_ext,使用$i代表box0,$j代表http.请记住,$i也可以是box1 / box2,$j也可以替换为ftp / telnet / ssh.

解决方法

您可以使用间接变量参考来实现(参见 http://tldp.org/LDP/abs/html/bashver2.html#EX78)

这在Bash Version 2及更高版本中可用,使用!在变量名之前,在${}内.

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

工作范例:

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

输出:

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

在上面的示例中,$name返回sting box0_http_port_ext,它是初始变量的名称.这相当于${name}.的! operator将字符串作为变量名称计算在其右侧,并返回存储在变量中的值.所以${!name}返回${box0_http_port_ext}的值,即hello1.

不幸的是,bash不支持多维数组,但可以使用这个技巧.

与其他答案的区别在于$i_ $j_port_ext更改为${i} _ ${j} _port_ext,以便bash知道变量名称的结束位置.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读