Environment Variables Required Validation
Validate required environment variables upfront with parameter expansion guards, checking formats before any side effects.
Code
#!/usr/bin/env bash
set -euo pipefail
# 必填变量在脚本最顶端集中校验
require_env() {
local name="$1"
local pattern="${2:-}"
local value="${!name:-}"
if [[ -z "${value}" ]]; then
echo "Error: 必填环境变量 ${name} 未设置" >&2
return 1
fi
if [[ -n "${pattern}" && ! "${value}" =~ ${pattern} ]]; then
echo "Error: 环境变量 ${name} 格式非法: ${value}" >&2
return 1
fi
}
validate_all() {
local failed=0
require_env "DEPLOY_ENV" '^(staging|production)$' || failed=1
require_env "DATABASE_URL" '^postgres://' || failed=1
require_env "API_TOKEN" '.{20,}' || failed=1
require_env "MAX_REPLICAS" '^[0-9]+$' || failed=1
if (( failed )); then
echo "Error: 环境校验失败,请在启动前修正上述变量" >&2
exit 1
fi
}
validate_all
readonly ENVIRONMENT="${DEPLOY_ENV}"
readonly REPLICAS="${MAX_REPLICAS}"
echo "配置校验通过:${ENVIRONMENT} 环境,副本数 ${REPLICAS}"
echo "数据库目标:${DATABASE_URL%%\?*}"
What the code does
set -euo pipefail puts the script into strict mode: it stops on the first failing command, treats unset variables as errors, and fails a pipeline if any stage fails.
The work is delegated to require_env and readonly, chained through 9 pipes so each stage’s output feeds the next.
2 helper functions (require_env and validate_all) keep the repeated logic out of the main flow.
The script leans on parameter expansion 14 times, using forms like ${var:-default}, ${var%%suffix} so defaults, trimming, and casing happen inside the shell with no external tool.
Points of care
- The pipeline is 9 stages deep — when it misbehaves, split the pipe and test the stages separately.
The key statements, annotated
require_env "DEPLOY_ENV" '^(staging|production)$' || failed=1
require_env "DATABASE_URL" '^postgres://' || failed=1
require_env "API_TOKEN" '.{20,}' || failed=1
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
- Which external commands does the script rely on?
- `require_env`, `readonly` must be available on the PATH environment variable; everything else is shell built-in syntax.
Report a problem with this exampleOpens a pre-filled issue on GitHub.