Bash从外部文件读取数组 [英] Bash read array from an external file
问题描述
我已经设置了一个Bash菜单脚本,该脚本也需要用户输入. 这些输入被写入(附加到)名为var.txt的文本文件中,如下所示:
I have setup a Bash menu script that also requires user input. These inputs are wrote (appended to) a text file named var.txt like so:
input[0]='192.0.0.1'
input[1]='username'
input[2]='example.com'
input[3]='/home/newuser'
现在我要完成的工作是能够从类似这样的脚本中读取var.txt:
Now what I am trying to accomplish is to be able to read from var.txt from a script kinda like this:
useradd var.txt/${input[1]}
现在我知道仅以它为例就行不通了.
now I know that wont work just using it for an example.
在此先感谢您, 乔
推荐答案
您可以将变量提取封装在函数中,并利用declare
在函数内部使用时会创建局部变量这一事实.每次调用该函数时,该技术都会读取文件.
You can encapsulate your variable extraction in a function and take advantage of the fact that declare
creates local variables when used inside a function. This technique reads the file each time the function is called.
readvar () {
# call like this: readvar filename variable
while read -r line
do
# you could do some validation here
declare "$line"
done < "$1"
echo ${!2}
}
给出一个名为数据"的文件,其中包含:
Given a file called "data" containing:
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
这将读取一个数组并将其重命名:
This will read an array and rename it:
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
这样做,您只需要对函数进行一次调用即可使用整个数组,而不必进行单独的查询.
Doing it this way, you would only need to make one call to the function and the entire array would be available instead of having to make individual queries.
这篇关于Bash从外部文件读取数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!