Skip to content

Instantly share code, notes, and snippets.

@rodmhgl
Last active September 6, 2023 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodmhgl/4d6953ada2b6397c977bf019de6178d0 to your computer and use it in GitHub Desktop.
Save rodmhgl/4d6953ada2b6397c977bf019de6178d0 to your computer and use it in GitHub Desktop.
Export environment variables matching a string to a file to be sourced later
#!/usr/bin/env bash
# pilfered from a MSFT AKS tutorial and tweaked
if [ "$#" -ne 2 ]; then
echo "Will export env variables that end with <search_string>"
echo "Usage: $0 <search_string> <output_filename>"
exit 1
fi
dir_name=$(dirname "$0")
env_search="$1"
env_export_filename="$2"
output_path="$dir_name/$env_export_filename"
if ! touch "$output_path" > /dev/null 2>&1; then
echo "Error: Cannot write to $output_path"
exit 1
fi
cat > $output_path << EOF
#!/usr/bin/env bash
$(env | sed -n "s/\(.*$ENV_SEARCH=\)\(.*\)/export \1'\2'/p" | sort)
EOF
cat $output_path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment