Parse command-line flags `-e <env>`, `-v` (verbose) and `-h` in a Bash script.
IntermediateHands-onBash scripting tasks
Answer
#!/usr/bin/env bash
set -euo pipefail
ENV=""; VERBOSE=0
usage() { echo "Usage: $0 -e <env> [-v]"; exit 1; }
while getopts ":e:vh" opt; do
case "$opt" in
e) ENV="$OPTARG" ;;
v) VERBOSE=1 ;;
h) usage ;;
:) echo "Option -$OPTARG needs a value" >&2; usage ;;
\?) echo "Unknown option -$OPTARG" >&2; usage ;;
esac
done
shift $((OPTIND - 1))
[ -z "$ENV" ] && usage
(( VERBOSE )) && echo "Deploying to $ENV, remaining args: $*"
Key trick → The leading : in ":e:vh" turns on silent error mode so you handle : (missing value) and ? (unknown flag) yourself.
More on Bash scripting tasks
Write the safe header you start every Bash script with, and explain each part.BeginnerWrite a script that alerts when any filesystem is above 80% usage.BeginnerParse an Nginx access log and print the top 10 client IPs by request count.BeginnerWrite a backup script that tars a directory with a timestamp and keeps only the last 7 backups.IntermediateWrite a health-check loop that polls a URL until it returns 200, with a timeout.IntermediateUse `trap` to clean up a temp directory on exit, even on Ctrl+C or error.Intermediate