Shell读取配置文件、修改配置文件(ini、conf)

本文详细介绍了如何使用Shell脚本来读取、修改配置文件,提供了一个优秀的脚本示例,用于读取或更新.ini配置文件的内容。通过示例代码展示了如何查找特定section的key并打印或更新其value,对于日常的配置文件管理和自动化任务非常实用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

读取配置文件

配置文件:cba.ini

Shell脚本:abc.sh

运行脚本

运行结果

修改配置文件

运行脚本

注:

优秀代码

配置文件 conf.ini

读、修配置文件脚本

参考博客


读取配置文件

配置文件:cba.ini

[Class]
ids=student1,student2,student3
files=profilefile
 
[student1]
name=LiLei
age=16
 
[student2]
name=HanMeiMei
age=15
 
[student3]
name=Lucy
age=15

Shell脚本:abc.sh

#/usr/bin/env bash

base_path=$(cd `dirname $0`; pwd)
cba_ini=$base_path/cba.ini

aaa=`awk -F '=' '/\[student1\]/{a=1}a==1&&$1~/name/{print $2;exit}' $cba_ini`
echo $aaa

运行脚本

bash abc.sh

运行结果

[root@localhost opt]# bash abc.sh 
LiLei

修改配置文件

运行脚本

#/usr/bin/env bash

base_path=$(cd `dirname $0`; pwd)
cba_ini=$base_path/cba.ini
name=gege

awk -F "=" '/\[student2\]/{a=1} (a==1 && "name"==$1){gsub($2,"'${name}'");a=0} {print $0}' $cba_ini 1<>$cab_ini

注:

        配置文件中的 "=" 号旁边是否有空格,-F 后的 "=" 一定要同步

优秀代码

配置文件 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 = 222
run = 0
env = dev

读、修配置文件脚本

#!/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 【<get|set> <file> <section> <key> [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
    echo $delimeter ${section} ${key} ${val} ${file}
    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

参考博客

https://blog.csdn.net/qq_42761569/article/details/121969825

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

墨痕诉清风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值