shell脚本读写ini配置文件

Background

  • INI文件是Initialization File的缩写,即初始化文件。
  • INI文件由节(section)、键(key)、值(value)三部分组成。
  • 这里封装了一个脚本实现了对ini配置文件的指定section指定key的value的读取或更新

1、实现效果

shell脚本读写ini配置文件_第1张图片

2、源码 ini-operator.sh

注意: 我用的配置文件中key和value的分隔符是【空格等号空格】,即等号两边有空格,使用的时候注意一下。

#!/bin/bash  

:<<!
【脚本说明】
1、此脚本适用操作.ini配置文件内容;
2、可以读取或更新指定section指定key的value;
!

# key和value的分隔符,即等号两边有没有空格
#delimeter='='
delimeter=' = '

# 操作参数
operate=$1
# 操作文件
file=$2
# 指定section
section=$3
# 指定key
key=$4
# value
value=$5

# 提示信息
msg="Please input the param 【  
[value]】" # 定制化shell输出 function custom_print(){ echo -e "\033[5;34m ***** \033[0m" echo -e "\033[32m $@ ! \033[0m" echo -e "\033[5;34m ***** \033[0m" } # 获取配置文件指定section指定key的value function get_opt() { file=$1 section=$2 key=$3 val=$(awk -F "$delimeter" '/\['${section}'\]/{a=1}a==1&&$1~/'${key}'/{print $2;exit}' $file) echo ${val} } # 更新配置文件指定section指定key的value function set_opt() { file=$1 section=$2 key=$3 val=$4 awk -F "$delimeter" '/\['${section}'\]/{a=1} (a==1 && "'${key}'"==$1){gsub($2,"'${val}'");a=0} {print $0}' ${file} 1<>${file} } # 判断输入参数 if [[ -z $operate || $operate = "help" || $operate = "-h" || -z $section || -z $key ]]; then custom_print $msg elif [[ $operate = "get" ]]; then val=$(get_opt $file $section $key) echo $val elif [[ $operate = "set" && $value ]]; then set_opt $file $section $key $value msg='update success' custom_print $msg else custom_print $msg fi

3、另附例子中所用的文件 conf.ini

[p1]
settings = settings_p1
port = 8001
run = 1
env = dev

[p2]
settings = settings_p2
port = 8002
run = 0
env = dev

[p3]
settings = settings_p3
port = 8003
run = 0
env = dev

你可能感兴趣的:(Linux,bash,linux,读写ini配置文件)