Linux shell script modifies the key value under the ini configuration file [session]

For example, I want to modify a configuration file, as follows, modify the ip and port values ​​​​under [huake] under systemFlag.ini
Insert image description here
The code is as follows, I will not explain it, there is Comments are modified using sed. If you don’t understand, you can learn it

#!/bin/bash  
  
#获取当前路径
currentPath=$(cd `dirname $0`; pwd)
# 配置文件路径  
config_file="$currentPath/systemFlag.ini"  
  
# 设置新的IP和端口值  \表示特殊符合处理,转义符
new_ip="47.98.173.88\/agpt\/safetymanagement\/rest\/api\/net-agpt"
new_port="55555"

# 检查配置文件是否存在  
if [ ! -f "$config_file" ]; then  
  echo "Error: $config_file does not exist!"  
  exit 1  
fi  
  
# 打印调试信息  
echo "Config file path: $config_file"  
echo "New IP value: $new_ip"  
echo "New Port value: $new_port"  
  
# 使用sed命令修改配置文件中【huake】下的ip和port的值  
#sed -i -e "s/^\[huake\]$/\[huake\]\nip=${new_ip}\nport=$new_port/" "$config_file"  #追加
# 替换
sed -i '/\[huake\]/,/\[.*\]/ s/ip=.*$/ip='${new_ip}'/' "${config_file}"
sed -i '/\[huake\]/,/\[.*\]/ s/port=.*$/port='${new_port}'/' "${config_file}"

echo "配置文件修改成功."
notify-send "$config_file 配置文件修改成功"

Execute the script and it will prompt that the modification is successful!
Insert image description here

Guess you like

Origin blog.csdn.net/qq_44667165/article/details/134074856