Shell 实现读取ini格式配置文件

ini文件格式一般都是由节、键、值三部分组成。

格式:
[第一节 ]
第一个键 = 值
第二个键 = 第二个值
[第二节 ]
第一个键 = val1,val2,val3

[redis]
host = xxx
port = xx
backend_db = xx
broker_db = xx

[mysql]
root_passwd = xxxx
passwd = xxxxx
charset = xxxxx
db = xxxx

shell 脚本读取方式
创建readIni()函数,$1,$2,$3为传递的参数,文件名($1),模块字段名($2),键key($3),根据这三个参数读取ini文件中指定的模块字段中key对应的value值

#!/bin/bash

#!/bin/bash

readIni() {
  ini_file=$1
  section=$2
  option=$3
  default_value=$4
  python -c "exec(\"import os,sys;\ntry:\n\timport ConfigParser;\nexcept:\n\timport configparser as ConfigParser;\n\
ini_file='${ini_file}';section='${section}';option='${option}';default_value='${default_value}';\
cp=ConfigParser.ConfigParser();cp.read(ini_file);\n\
try:\n\t\
if cp.has_section(section) and cp.has_option(section,option):\n\t\tprint(cp.get(section,option));\n\t\
else:\n\t\tprint(default_value);\n\
except Exception as e:\n\tprint(default_value)\")"
  #file=$1;section=$2;item=$3;
  #ret=`awk -F '=' '/\['$section'\]/{a=1}a==1&&$1~/'$item'/{gsub(/#.*/,"",$2);gsub(/;.*/,"",$2);gsub(/\"/,"",$2);printf("%s\t",$2) ;exit}' $file`
  #val=`echo ${ret}|sed 's/\r//g'`
  #echo ${val}
}

readIniSections() {
  file=$1
  val=$(awk '/\[/{printf("%s ",$1)}' ${file} | sed 's/\[//g' | sed 's/\]//g')
  echo ${val}
}

function WriteIni() {
  ini_file=$1
  section=$2
  option=$3
  value=$4

  python -c "exec(\"import os,sys;\ntry:\n\timport ConfigParser;\nexcept:\n\timport configparser as ConfigParser;\n\
ini_file='${ini_file}';section='${section}';option='${option}';value='${value}';\
cp=ConfigParser.ConfigParser();cp.read(ini_file);\n\
try:\n\t\
cp.set(section, option, value);\n\t\
cp.write(open(ini_file, 'w+'));\n\
except Exception as e:\n\tprint('write ini file error: ', e)\")"

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值