一、创建一个配置文件
创建一个 config.ini 配置文件,内容如下:
配置文件的格式如下:
[段名1]
Key1=Value1
Key2=Value2
Key3=Value3
...
[段名2]
Key4=Value4
Key5=Value5
Key6=Value6
[root@localhost Shire_Diag_tool]# cat config.ini
[General]
product_date="2022/05/05"
test_server_ip="192.168.89.100"
upgrade_file_path="./upgrade/"
image_file_name="image.ub"
boot_file_name="boot.bin"
fsbl_file_name="fsblboot.bin"
二、解析配置文件
利用 awk 工具解析文件的每一行,这要求配置文件的每一行的格式必须一致,否则会导致解析不到相关的关键字和值。
编写一个解析配置文件的 shell 脚本示例:config.sh
[root@localhost Shire_Diag_tool]# cat config.sh
#!/bin/bash
gConfigFile="./config.ini"
gSection="General"
gFail="FAIL" # Suggestion: avoid needing to match too many false strings, use only one string "FAIL"
function help()
{
local ini_cnt=`cat $gConfigFile | grep = -c`
echo -e "\033[32m Usage: \033[0m"
for ((i=1;i<=$ini_cnt;i++))
do
key=`awk -F '=' '/\['$gSection'\]/{a=1} {if (a==1&&NR==('$i'+1)) print $1}' $gConfigFile`
echo -e "\033[32m $0 $key \033[0m"
done
}
function ReadINIfile()
{
key=$1
section=$2
configfile=$3
cat $configfile | grep $key -w >/dev/null 2>&1
if [[ $? -ne 0 ]];then
echo "$gFail"
return 1
fi
ReadINI=`awk -F '=' '/\['$section'\]/{a=1} a==1&&$1~/'$key'/ {print $2;exit}' $configfile`
echo "$ReadINI"
return 0
}
function main()
{
argv1=$1
itemCount=`ReadINIfile "$argv1" "$gSection" "$gConfigFile"`
#itemCount=`ReadINIfile "ItemCount" "General" "$configFile"`
echo "$argv1:$itemCount"
return 0
}
gRet=0
echo -e "\033[32m config.sh start \033[0m"
if [[ ! -e $gConfigFile ]];then
echo -e "\033[31m $gFail: $gConfigFile is not exist! \033[0m"
gRet=1
elif [[ $# -eq 0 ]] || [[ $# -gt 1 ]];then
help
gRet=1
elif [[ $1 = "?" ]] || [[ $1 = "help" ]] || [[ $1 = "h" ]];then
help
gRet=1
else
main $1
gRet=0
fi
echo -e "\033[32m config.sh end \033[0m"
exit $gRet
[root@localhost Shire_Diag_tool]#
三、效果演示
[root@localhost Shire_Diag_tool]# ./config.sh
config.sh start
Usage:
./config.sh product_date
./config.sh test_server_ip
./config.sh work_dir
./config.sh upgrade_file_path
./config.sh image_file_name
./config.sh boot_file_name
./config.sh fsbl_file_name
./config.sh cpld_bin_file
./config.sh x86sh_file_name
./config.sh fpfwup_file_name
./config.sh cpfwup_file_name
./config.sh prompt_srvos
./config.sh ali_nvme_test_file_name
config.sh end
[root@localhost Shire_Diag_tool]# ./config.sh a
config.sh start
a:FAIL
config.sh end
[root@localhost Shire_Diag_tool]# ./config.sh upgrade_file_path
config.sh start
upgrade_file_path:"./upgrade/"
config.sh end
[root@localhost Shire_Diag_tool]#