if ! type "include" > /dev/null 2>&1; then include() { . "$(cd "$(dirname "$1")" && pwd)/${2}"; }; fi include "${BASH_SOURCE[0]}" ../pragma_once.bash if ! pragma_once ${BASH_SOURCE[0]}; then return 0; fi include "${BASH_SOURCE[0]}" ./global_rely/export.bash include "${BASH_SOURCE[0]}" ./other.bash # shellcheck source=./global_rely/export.bash # shellcheck source=./other.bash # ========================= # template.bash # 纯 Bash 模板渲染 # 占位符格式: {{KEY}} # ========================= # 判断某个 key 是否合法 _template_validate_key() { local key="$1" [[ "$key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] } # 转义 replacement,避免 sed 替换时特殊字符出问题 _template_escape_replacement() { local s="$1" s="${s//\\/\\\\}" s="${s//&/\\&}" s="${s//|/\\|}" printf '%s' "$s" } # 核心:对一个字符串做渲染 # 用法: # template_render_string "hello {{NAME}}" NAME "wyc" AGE "18" template_render_string() { if [ $# -lt 1 ]; then echo "template_render_string: missing template string" >&2 return 1 fi local template_str="$1" shift if [ $(( $# % 2 )) -ne 0 ]; then echo "template_render_string: key/value arguments must be paired" >&2 return 1 fi local rendered="$template_str" local key="" local value="" local escaped_value="" while [ $# -gt 0 ]; do key="$1" value="$2" shift 2 if ! _template_validate_key "$key"; then echo "template_render_string: invalid key: $key" >&2 return 1 fi escaped_value="$(_template_escape_replacement "$value")" rendered="$(printf '%s' "$rendered" | sed "s|{{${key}}}|${escaped_value}|g")" done printf '%s' "$rendered" } # 从模板文件渲染到 stdout # 用法: # template_render_file /tmp/a.tpl NAME "wyc" AGE "18" template_render_file() { if [ $# -lt 1 ]; then echo "template_render_file: missing template file" >&2 return 1 fi local template_file="$1" shift if [ ! -f "$template_file" ]; then echo "template_render_file: template file not found: $template_file" >&2 return 1 fi local content="" content="$(cat "$template_file")" || return 1 template_render_string "$content" "$@" } # 从模板文件渲染到目标文件 # 用法: # template_render_to_file /tmp/a.tpl /tmp/out.conf NAME "wyc" template_render_to_file() { if [ $# -lt 2 ]; then echo "template_render_to_file: usage: template_render_to_file