Use env to locate bash, then fail fast on errors, unset vars and pipeline failures
#!/usr/bin/env bash
set -euo pipefailBash scripting essentials: variables and parameter expansion, conditionals, loops, functions and arrays, robust set -euo pipefail and trap patterns, plus awk, sed and getopts recipes.
Use env to locate bash, then fail fast on errors, unset vars and pipeline failures
#!/usr/bin/env bash
set -euo pipefailNo spaces around =, and brace variable references to avoid ambiguous names
APP_ENV="prod"
echo "deploy to ${APP_ENV}":- supplies a default, :? aborts with a message for required values
PORT="${PORT:-8080}"
NAME="${NAME:?NAME is required}"$# counts args, $1 is the first; always loop with "$@" to keep spaces intact
echo "args=$# first=$1 all=$*"
for arg in "$@"; do echo "$arg"; doneUse $( ) for command substitution; it nests and reads better than backticks
NOW=$(date +%F)
FILES=$(ls *.log | wc -l)[[ ]] supports && and patterns and is safer than [ ] for file tests
if [[ -f "$CONF" && -r "$CONF" ]]; then
echo "readable"
else
echo "missing" >&2
exit 1
fiMulti-branch dispatch for subcommands; ;; acts as break
case "$1" in
start) echo start ;;
stop) echo stop ;;
*) echo "usage: $0 start|stop" ;;
esacGlobs stay literal when unmatched, so check existence inside the loop
for f in /var/log/*.log; do
[[ -e "$f" ]] || continue
echo "$f"
doneRead line by line; IFS= and -r preserve whitespace and backslashes
while IFS= read -r line; do
echo "$line"
done < hosts.txtC-style for loops and arithmetic expansion with (( ))
for ((i = 0; i < 3; i++)); do echo "$i"; done
((count++))Declare locals inside functions to avoid leaking into the global scope
log() {
local level="$1"
shift
echo "[$level] $*" >&2
}
log INFO "started"Index and count array items; quote expansions when looping
hosts=(web1 web2 web3)
echo "${hosts[0]} ${#hosts[@]}"
for h in "${hosts[@]}"; do echo "$h"; doneAssociative arrays need Bash 4 or newer
declare -A ports=([web]=80 [api]=8080)
echo "${ports[api]}"
for k in "${!ports[@]}"; do echo "$k=${ports[$k]}"; doneExit on error, fail on unset vars and propagate pipeline failures
set -euo pipefailBehavior shifts inside if conditions and substitutions; mind exit code checks.
Clean up temp resources on both normal exit and interruption
cleanup() {
rm -rf "$TMP_DIR"
}
trap cleanup EXIT[[ ]] for strings and globs, [ ] with -gt and -lt for numeric tests
[[ "$name" == *.log ]]
[ "$count" -gt 10 ]Static checks for unquoted variables and invalid tests; worth running in CI
shellcheck deploy.shgrep counts matches, awk extracts fields; the most common log analysis combo
grep -c "ERROR" app.log
awk '{print $1, $4}' access.log | headIn-place replace with a .bak copy so a bad edit can be reverted
sed -i.bak 's/localhost/127.0.0.1/g' app.confTop-10 frequency pipeline for busiest IPs or endpoints
sort access.log | uniq -c | sort -rn | head -10Parse short flags like -e prod -p 8080 in small to medium scripts
while getopts ":e:p:" opt; do
case "$opt" in
e) ENV="$OPTARG" ;;
p) PORT="$OPTARG" ;;
*) exit 2 ;;
esac
doneThis website uses cookies to ensure you get the best experience on our website. Privacy Policy.