需求:
完整地读取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命令执行,从而将它们设置为环境变量。