shell读取config.ini文件
该脚本需要三个参数,第一个为文件名,第二个为章节名称,第三个为字段名称
#!/bin/bash
iniFile=$1
section=$2
option=$3
function readInIfile()
{
iniFile=$1
section=$2
option=$3
if [ "${section}" = "" ];then
#通过如下两条命令可以解析成一个数组
allSections=$(awk -F '[][]' '/[.*]/{print $2}' ${iniFile})
iniSections=(${allSections// /})
echo "[info]:iniSections size:-${#iniSections[@]}- eles:-${iniSections[@]}- "
return ${#iniSections[@]}
elif [ "${section}" != "" ] && [ "${option}" = "" ];then
#判断section是否存在
allSections=$(awk -F '[][]' '/[.*]/{print $2}' ${iniFile})
echo $allSections|grep ${section}
if [ "$?" = "1" ];then
echo "[error]:section --${section}-- not exist!"
return 0
fi
#正式获取options
#a=(获取匹配到的section之后部分|去除第一行|去除空行|去除每一行行首行尾空格|将行内空格变为@G@(后面分割时为数组时,空格会导致误拆))
a=$(awk "/[${section}]/{a=1}a==1" ${iniFile}|sed -e'1d' -e '/^$/d' -e 's/[ ]*$//g' -e 's/^[ ]*//g' -e 's/[ ]/@G@/g' -e '/[/,$d' )
b=(${a})
for i in ${b[@]};do
#剔除非法字符,转换@G@为空格并添加到数组尾
if [ -n "${i}" ]||[ "${i}" i!= "@G@" ];then
iniOptions[${#iniOptions[@]}]=${i//@G@/ }
fi
done
echo "[info]:iniOptions size:-${#iniOptions[@]}- eles:-${iniOptions[@]}-"
return ${iniOptions[@]}
elif [ "${section}" != "" ] && [ "${option}" != "" ];then
# iniValue=`awk -F '=' '/['${section}']/{a=1}a==1&&$1~/'${option}'/{print $2;exit}' $iniFile|sed -e 's/^[ ]*//g' -e 's/[ ]*$//g'`
iniValue=`awk -F '=' "/[${section}]/{a=1}a==1" ${iniFile}|sed -e '1d' -e '/^$/d' -e '/^[.*]/,$d' -e "/^${option}.*=.*/!d" -e "s/^${option}.*= *//"`
echo "[info]:iniValue value:-${iniValue}-"
return ${iniValue}
fi
}