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

Bash从外部文件读取数组

发布时间:2020-12-15 22:29:57 所属栏目:安全 来源:网络整理
导读:我已经设置了一个 Bash菜单脚本,也需要用户输入. 这些输入被写入(附加)一个名为var.txt的文本文件,如下所示: input[0]='192.0.0.1'input[1]='username'input[2]='example.com'input[3]='/home/newuser' 现在我想要完成的是能够从脚本中读取var.txt,如下所示
我已经设置了一个 Bash菜单脚本,也需要用户输入.
这些输入被写入(附加)一个名为var.txt的文本文件,如下所示:

input[0]='192.0.0.1'
input[1]='username'
input[2]='example.com'
input[3]='/home/newuser'

现在我想要完成的是能够从脚本中读取var.txt,如下所示:

useradd var.txt/${input[1]}

现在我知道只是用它来做一个例子.

提前致谢,

解决方法

您可以将变量提取封装在函数中,并利用declare在函数内部使用时创建局部变量的事实.每次调用函数时,此技术都会读取文件.

readvar () {
    # call like this: readvar filename variable
    while read -r line
    do
        # you could do some validation here
        declare "$line"
    done < "$1"
    echo ${!2}
}

给定一个名为“data”的文件,其中包含:

input[0]='192.0.0.1'
input[1]='username'
input[2]='example.com'
input[3]='/home/newuser'
foo=bar
bar=baz

你可以这样做:

$a=$(readvar data input[1])
$echo "$a"
username
$readvar data foo
bar

这将读取一个数组并重命名它:

readarray () {
    # call like this: readarray filename arrayname newname
    # newname may be omitted and will default to the existing name
    while read -r line
    do
        declare "$line"
    done < "$1"
    local d=$(declare -p $2)
    echo ${d/#declare -a $2/declare -a ${3:-$2}};
}

例子:

$eval $(readarray data input output)
$echo ${output[2]}
example.com
$echo ${output[0]}
192.0.0.1
$eval $(readarray data input)
$echo ${input[3]}
/home/newuser

这样做,您只需要对函数进行一次调用,整个数组就可以使用,而不必进行单独的查询.

(编辑:李大同)

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

    推荐文章
      热点阅读