## Show and set environment variables for a command

# Print the whole environment
env

# Print it sorted, which is easier to scan
env | sort

# Look for one variable
env | grep -i proxy

# Print one variable's value
printenv PATH

# Print several
printenv HOME USER SHELL

# Run a command with one variable set, without changing your shell
env DEBUG=1 ./myapp

# Set several
env DEBUG=1 LOG_LEVEL=trace ./myapp

# The shell can do the same thing more briefly
DEBUG=1 ./myapp

# Run with an empty environment
env -i /bin/bash --noprofile --norc

# Empty environment except what you name
env -i HOME="$HOME" PATH=/usr/bin ./myapp

# Remove one variable for this command
env -u HTTP_PROXY curl -s https://example.com

# Remove several
env -u HTTP_PROXY -u HTTPS_PROXY ./deploy.sh

# Change the working directory for the command
env -C /srv/app ./run.sh

# Split a long shebang argument list (the -S trick)
env -S "python3 -u -W ignore" script.py

# Export a variable for the rest of the shell session
export EDITOR=vim

# Export a variable built from another
export PATH="$HOME/.local/bin:$PATH"

# Unset a variable
unset HTTP_PROXY

# Show only variables the shell exported
export -p

# Load an env file into the current shell
set -a && . ./app.env && set +a

# Load an env file for one command only
env $(grep -v '^#' app.env | xargs) ./myapp

# Safer load, handling values with spaces
while IFS= read -r l; do [ -n "$l" ] && export "$l"; done < <(grep -v '^#' app.env)

# Write the current environment to a file
env | sort > env-snapshot.txt

# Compare two environments
diff <(env | sort) env-snapshot.txt

# The environment of a running process
sudo tr '\0' '\n' < /proc/4821/environ

# Environment of a process, one variable
sudo tr '\0' '\n' < /proc/4821/environ | grep PATH

# What systemd gives a service
systemctl show -p Environment nginx

# Set a variable for a systemd service
sudo systemctl edit nginx

# Pass variables into a container
docker run -e DEBUG=1 -e LOG_LEVEL=trace myimage

# Pass a whole env file into a container
docker run --env-file app.env myimage

# Environment inside a running container
docker exec web env

# Environment in a Kubernetes pod
kubectl exec deploy/web -- env

# Keep a variable across sudo, which strips most of them
sudo --preserve-env=HTTP_PROXY apt update

# Is a variable set, even if empty?
[ -n "${DEBUG+x}" ] && echo "DEBUG is set"

# Use a default when a variable is unset
echo "${LOG_LEVEL:-info}"
