docker/nginx/replace_vars.sh

69 lines
2.0 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
# 加载环境变量
source ../environment.sh
echo "开始替换配置文件中的环境变量..."
# 检查vhosts目录是否存在
if [ ! -d "vhosts" ]; then
echo "错误: vhosts目录不存在!"
exit 1
fi
# 检查vhosts目录中是否有配置文件
if [ -z "$(ls -A vhosts/*.conf 2>/dev/null)" ]; then
echo "警告: vhosts目录中没有.conf文件没有配置文件需要处理"
exit 0
fi
# 创建临时目录
TEMP_DIR="temp_vhosts"
rm -rf $TEMP_DIR
mkdir -p $TEMP_DIR
# 处理所有.conf文件替换环境变量跳过cert目录
for conf_file in vhosts/*.conf; do
# 检查文件是否存在(处理无匹配文件的情况)
if [ ! -f "$conf_file" ]; then
continue
fi
# 跳过cert目录中的文件
if [[ "$conf_file" == *"/cert/"* ]]; then
continue
fi
filename=$(basename "$conf_file")
echo "处理文件: $filename"
# 读取原始文件内容
content=$(cat "$conf_file")
# 获取所有环境变量包括export和非export的
# 使用set命令获取所有变量然后过滤出大写字母开头的变量
env_vars=$(set | grep -E "^[A-Z_]+=" | cut -d= -f1)
# 逐个替换环境变量
for var_name in $env_vars; do
# 使用eval获取变量值这样可以处理包含特殊字符的值
eval "var_value=\$$var_name"
if [ ! -z "$var_value" ]; then
# 使用更安全的变量替换方法
pattern="\\\${$var_name}"
# 转义特殊字符
escaped_value=$(echo "$var_value" | sed 's/[\/&]/\\&/g')
echo " 替换变量: ${pattern} -> $var_value"
content=$(echo "$content" | sed "s|${pattern}|${escaped_value}|g")
fi
done
# 写入处理后的内容到临时文件
echo "$content" > "$TEMP_DIR/$filename"
echo " 文件处理完成: $filename"
done
echo "环境变量替换完成! 替换后的文件位于 $TEMP_DIR/ 目录"
echo "请检查替换结果,确认无误后运行 build_image.sh 构建镜像"