问题描述
我试图读取格式的配置文件如下:
I'm attempting to read a config file that is formatted as follows:
USER = username
TARGET = arrows
我意识到,如果我摆脱了空间,我可以简单的将配置文件,但出于安全原因,我想避免这种情况。我知道有一种方法可以逐行读取配置文件行。我觉得这个过程是这样的:
I realize that if I got rid of the spaces, I could simply source the config file, but for security reasons I'm trying to avoid that. I know there is a way to read the config file line by line. I think the process is something like:
- 阅读行到一个数组
- 过滤掉所有以#开头的行
- 在数组中搜索该变量名
之后,我迷路了。任何及所有帮助将大大AP preciated。我已经试过这样的事情没有成功:
After that I'm lost. Any and all help would be greatly appreciated. I've tried something like this with no success:
backup2.config>cat ~/1
grep '^[^#].*' | while read one two;do
echo $two
done
我拉从一个论坛帖子,我发现,只是不知道如何修改它适合我的需要,因为我很新shell脚本。
I pulled that from a forum post I found, just not sure how to modify it to fit my needs since I'm so new to shell scripting.
http://www.linuxquestions.org/questions/programming-9/bash-shell-program-read-a-configuration-file-276852/
有没有可能来通过两个数组循环自动分配一个变量?
Would it be possible to automatically assign a variable by looping through both arrays?
for (( i = 0 ; i < ${#VALUE[@]} ; i++ ))
do
"${NAME[i]}"=VALUE[i]
done
echo $USER
这样调用$用户将输出用户名?以上code未工作,但我知道解决的办法是类似的东西。
Such that calling $USER would output "username"? The above code isn't working but I know the solution is something similar to that.
推荐答案
下面的脚本遍历各行中输入文件(瓦尔的在我的情况),并不会针对模式匹配 =
。如果等号发现它会使用解析出变量的名称的距离的值的。然后,它存储在它自己的阵列,名称的和的值的分别每一个部分。
The following script iterates over each line in your input file (vars in my case) and does a pattern match against =
. If the equal sign is found it will use Parameter Expansion to parse out the variable name from the value. It then stores each part in it's own array, name and value respectively.
#!/bin/bash
i=0
while read line; do
if [[ "$line" =~ ^[^#]*= ]]; then
name[i]=${line%% =*}
value[i]=${line#*= }
((i++))
fi
done < vars
echo "total array elements: ${#name[@]}"
echo "name[0]: ${name[0]}"
echo "value[0]: ${value[0]}"
echo "name[1]: ${name[1]}"
echo "value[1]: ${value[1]}"
echo "name array: ${name[@]}"
echo "value array: ${value[@]}"
输入
$ cat vars
sdf
USER = username
TARGET = arrows
asdf
as23
输出
$ ./varscript
total array elements: 2
name[0]: USER
value[0]: username
name[1]: TARGET
value[1]: arrows
name array: USER TARGET
value array: username arrows
这篇关于阅读BASH配置文件,而无需使用&QUOT;源&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!