MST
星途 面试题库

面试题:Bash脚本中如何实现对云原生应用配置文件的动态修改

假设你有一个云原生应用,其配置文件config.yml存放在 /app/config 目录下。该配置文件中有一个参数 "server_port",现在要求编写一个Bash脚本,能够根据用户输入动态修改这个配置文件中的 "server_port" 参数值,且要保证对yaml格式的正确处理。请写出实现该功能的Bash脚本代码。
44.6万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

# 检查用户是否提供了端口号参数
if [ -z "$1" ]; then
    echo "请提供要设置的server_port值作为参数"
    exit 1
fi

port=$1
config_file="/app/config/config.yml"

# 检查配置文件是否存在
if [ ! -f "$config_file" ]; then
    echo "配置文件 $config_file 不存在"
    exit 1
fi

# 使用yq工具修改server_port值(假设已安装yq)
yq eval -i ".server_port = $port" $config_file

echo "server_port已成功修改为 $port"

注意:上述脚本依赖 yq 工具来处理YAML文件。如果系统中未安装 yq,可以通过包管理器(如 brew install yq 对于MacOS,apt-get install yq 对于基于Debian的系统等)进行安装。如果不想使用 yq,也可以使用 sed 等工具,但处理YAML格式相对复杂一些,如下:

#!/bin/bash

if [ -z "$1" ]; then
    echo "请提供要设置的server_port值作为参数"
    exit 1
fi

port=$1
config_file="/app/config/config.yml"

if [ ! -f "$config_file" ]; then
    echo "配置文件 $config_file 不存在"
    exit 1
fi

# 使用sed修改server_port值
sed -i "s/^\(server_port:\s*\).*/\1$port/" $config_file

echo "server_port已成功修改为 $port"

sed 方法假设 server_port 配置项独立一行,且前面没有其他缩进层级。如果YAML结构更复杂,还是建议使用 yq 工具。