首页 > 系统服务 > 详细

Shell Script-读取配置文件

时间:2015-12-17 23:49:03      阅读:344      评论:0      收藏:0      [点我收藏+]

需求


有时候在shell script里面需要一些执行,如果放在程序里面不便于统一管理,并且每一次修改路径都要去script里面改好麻烦,所以统一把路径放在配置文件中方便管理。


问题


如何读取相对应的key-value是主要问题,主要是用到IFS分隔符,记住使用时最好先备份原来的IFS,使用完记得还原IFS,否则会出现未知错误


配置文件(格式:”key = value“)

1 [csv]
2 splitHome = 20151214_QL/split_home
3 output = 20151214_QL/output

读取代码(判断配置文件是否存在----备份IFS-----读取并输出想要结果-------还原IFS)

 1 #!/bin/bash
 2 
 3 #config file
 4 config="config.ini"
 5 
 6 #judge whether config.ini exists or not.
 7 if [ ! -f "$config" ];then
 8         echo "the file of config.ini not exist"
 9         exit 0
10 fi
11 
12 #save the old IFS
13 OLDIFS=$IFS
14 
15 #set the IFS which is used to split the key-value
16 IFS=" = "
17 
18 split="splitHome"
19 output="output"
20 
21 s=""
22 o=""
23 
24 while read -r name value
25 do
26 if [[ "$name" = *$split* ]]; then
27         s=$value
28 elif [[ "$name" = *$output* ]];then
29         o=$value
30 fi
31 done < $config
32 
33 #output the result
34 echo $s
35 echo $o
36 
37 #reset the IFS
38 IFS=$OLDIFS
39 ~

命令行输出结果

1 20151214_QL/split_home
2 20151214_QL/output

 

Shell Script-读取配置文件

原文:http://www.cnblogs.com/loadofleaf/p/5055559.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!