kangda-robot-backend/ruoyi-fastapi-backend/load_env.sh
2026-01-30 15:39:59 +08:00

68 lines
1.4 KiB
Bash

#!/usr/bin/env bash
set -euo pipefail
ENV_NAME="${1:-dev}"
ENV_FILE=".env.${ENV_NAME}"
if [[ ! -f "${ENV_FILE}" ]]; then
echo "Env file not found: ${ENV_FILE}" >&2
exit 1
fi
shift || true
_export_env_file() {
local file="$1"
while IFS= read -r line || [[ -n "$line" ]]; do
# trim
line="${line#${line%%[![:space:]]*}}"
line="${line%${line##*[![:space:]]}}"
[[ -z "$line" ]] && continue
[[ "$line" == \#* ]] && continue
# must contain '='
if [[ "$line" != *"="* ]]; then
continue
fi
local key="${line%%=*}"
local val="${line#*=}"
# trim key/val
key="${key#${key%%[![:space:]]*}}"
key="${key%${key##*[![:space:]]}}"
val="${val#${val%%[![:space:]]*}}"
val="${val%${val##*[![:space:]]}}"
[[ -z "$key" ]] && continue
# strip inline comment (simple)
if [[ "$val" == *"#"* ]]; then
val="${val%%#*}"
val="${val%${val##*[![:space:]]}}"
fi
# strip quotes
if [[ ${#val} -ge 2 ]]; then
local first="${val:0:1}"
local last="${val: -1}"
if [[ "$first" == "$last" && ( "$first" == '"' || "$first" == "'" ) ]]; then
val="${val:1:${#val}-2}"
fi
fi
export "${key}=${val}"
done < "$file"
}
_export_env_file "${ENV_FILE}"
if [[ $# -gt 0 ]]; then
exec "$@"
else
echo "Loaded ${ENV_FILE}. Starting an interactive shell..." >&2
exec bash
fi