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)\")"
}