从外部文件猛砸读阵列 [英] Bash Read Array from External File
问题描述
我已经建立了猛砸菜单脚本,还要求用户输入。
这些输入写(附加)命名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.
在此先感谢,
乔
Thanks in Advance, Joe
推荐答案
您可以封装你的变量提取的功能,走的事实,即声明
创建局部变量函数内使用时。该技术读取文件中的每个函数被调用的时间。
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.
这篇关于从外部文件猛砸读阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!