shell脚本如何读取ini配置文件(已测试正常运行)

需求:
完整地读取INI配置文件中某个节点下的所有属性,并将它们设置为环境变量供脚本使用,首先尝试从脚本所在目录下的"config.ini"读取配置,如果不存在,则从用户目录下的"~/.config.ini"读取配置

代码如下:

#!/bin/bash

# Function to read INI file and extract values of a specific section
read_ini_section() {
    local section="$1"
    local config_file="$2"

    awk -F '=' -v section="$section" '
        # Ignore lines starting with ";" or "#"
        !/^[[:space:]]*([;#]|$)/ {
            # If the current line starts a new section, update the current section
            if ($1 ~ /^\[[[:alnum:]_]+\]$/) {
                current_section = $1
            } else if (current_section == "["section"]") {
                # If the line belongs to the desired section, print the key-value pair
                gsub(/^[[:space:]]+|[[:space:]]+$/, "", $1)
                gsub(/^[[:space:]]+|[[:space:]]+$/, "", $2)
                print $1"="$2
            }
        }
    ' "$config_file"
}

# Try to read from the script's config.ini
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
script_config="$script_dir/config.ini"

# If the script's config.ini does not exist, read from the user's ~/.config.ini
if [[ ! -f "$script_config" ]]; then
    user_config="$HOME/.config.ini"
    if [[ -f "$user_config" ]]; then
        script_config="$user_config"
    else
        echo "Error: No config.ini found in script directory or user's home directory."
        exit 1
    fi
fi

# Specify the section you want to read
section="server"

# Read and set the configuration values as environment variables
eval "$(read_ini_section "$section" "$script_config")"

# Now, you can use the environment variables in your script
echo "Server Address: $address"
echo "Server Port: $port"

ini配置文件内容如下:

; Sample config.ini file
[server]
address = 192.168.1.100
port = 8080

[timeout]
connection = 30
read = 10

脚本定义了一个名为read_ini_section的函数。该函数接受一个参数section,然后使用awk命令找到整个给定节点(section)的所有键值对,并打印出它们。然后,我们使用eval命令将输出的键值对作为Shell命令执行,从而将它们设置为环境变量。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值