做個shell解析ini檔案,用作搭建HA架構中的解析ini設定檔
測試的ini檔案是系統裡面搜到的一個
# Example driver definitions# Driver from the postgresql-odbc package# Setup from the unixODBC package[PostgreSQL]Description= ODBC for PostgreSQLDriver= /usr/lib/psqlodbc.soSetup= /usr/lib/libodbcpsqlS.soDriver64= /usr/lib64/psqlodbc.soSetup64= /usr/lib64/libodbcpsqlS.soFileUsage= 1# Driver from the mysql-connector-odbc package# Setup from the unixODBC package[MySQL]Description= ODBC for MySQLDriver= /usr/lib/libmyodbc5.soSetup= /usr/lib/libodbcmyS.soDriver64= /usr/lib64/libmyodbc5.soSetup64= /usr/lib64/libodbcmyS.soFileUsage= 1
iniparser.sh指令碼主要就兩個函數一個檢查ini檔案是否合法,另一個是去讀取值的
該指令碼主要為其它指令碼提供這兩個函數,處理是不會放在該指令碼內的,最後四行是簡單測試用的
#!/bin/bash#傳入參數 檔案名稱#傳回值 0,合法;其他值非法或出錯function check_syntax(){if [ ! -f $1 ];then return 1firet=$(awk -F= 'BEGIN{valid=1}{#已經找到非法行,則一直略過處理if(valid == 0) next#忽略空行if(length($0) == 0) next#消除所有的空格gsub(" |\t","",$0)#檢測是否是注釋行head_char=substr($0,1,1)if (head_char != "#"){#不是欄位=值 形式的檢測是否是塊名if( NF == 1){b=substr($0,1,1)len=length($0)e=substr($0,len,1)if (b != "[" || e != "]"){valid=0}}else if( NF == 2){#檢測欄位=值 的欄位開頭是否是[b=substr($0,1,1)if (b == "["){valid=0}}else{#存在多個=號分割的都非法valid=0}}}END{print valid}' $1)if [ $ret -eq 1 ];thenreturn 0elsereturn 2fi}#參數1 檔案名稱#參數2 塊名#參數3 欄位名#返回0,表示正確,且能輸出字串表示找到對應欄位的值#否則其他情況都表示未找到對應的欄位或者是出錯function get_field_value(){if [ ! -f $1 ] || [ $# -ne 3 ];thenreturn 1fiblockname=$2fieldname=$3begin_block=0end_block=0cat $1 | while read linedoif [ "X$line" = "X[$blockname]" ];thenbegin_block=1continuefiif [ $begin_block -eq 1 ];thenend_block=$(echo $line | awk 'BEGIN{ret=0} /^\[.*\]$/{ret=1} END{print ret}')if [ $end_block -eq 1 ];then#echo "end block"breakfineed_ignore=$(echo $line | awk 'BEGIN{ret=0} /^#/{ret=1} /^$/{ret=1} END{print ret}')if [ $need_ignore -eq 1 ];then#echo "ignored line:" $linecontinuefifield=$(echo $line | awk -F= '{gsub(" |\t","",$1); print $1}')value=$(echo $line | awk -F= '{gsub(" |\t","",$2); print $2}')#echo "'$field':'$value'"if [ "X$fieldname" = "X$field" ];then#echo "result value:'$result'"echo $valuebreakfifidonereturn 0}check_syntax odbcinst.iniecho "check syntax status:$?"GLOBAL_FIELD_VALUE=$(get_field_value odbcinst.ini PostgreSQL Setup)echo "status:$?,value:$GLOBAL_FIELD_VALUE"