
正文
Shell Script-读取配置文件
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
需求
有时候在shell script里面需要一些执行,如果放在程序里面不便于统一管理,并且每一次修改路径都要去script里面改好麻烦,所以统一把路径放在配置文件中方便管理。
问题
如何读取相对应的key-value是主要问题,主要是用到IFS分隔符,记住使用时最好先备份原来的IFS,使用完记得还原IFS,否则会出现未知错误
配置文件(格式:”key = value“)
[csv]
splitHome = 20151214_QL/split_home
output = 20151214_QL/output
读取代码(判断配置文件是否存在----备份IFS-----读取并输出想要结果-------还原IFS)
#!/bin/bash #config file
config="config.ini" #judge whether config.ini exists or not.
if [ ! -f "$config" ];then
echo "the file of config.ini not exist"
exit 0
fi #save the old IFS
OLDIFS=$IFS #set the IFS which is used to split the key-value
IFS=" = " split="splitHome"
output="output" s=""
o="" while read -r name value
do
if [[ "$name" = *$split* ]]; then
s=$value
elif [[ "$name" = *$output* ]];then
o=$value
fi
done < $config #output the result
echo $s
echo $o #reset the IFS
IFS=$OLDIFS
~
命令行输出结果
20151214_QL/split_home
20151214_QL/output






![【电子书】[职业技术] 《Linux命令行与shell脚本编程大全(第3版)》[Richard Blum][epub+mobi+azw3] 【电子书】[职业技术] 《Linux命令行与shell脚本编程大全(第3版)》[Richard Blum][epub+mobi+azw3]](https://www.04ip.com/template/qe/style/noimg/15.jpg)

