Bash Scripting
Bash Scripting
8 interactive questions
What is `set -euo pipefail` and why use it?
-e — exit on any command failure. -u — error on undefined variables. -o pipefail — pipeline fails if any command fails (not just the last). 🎯 Put at top of every script for safety.
How do you handle errors and cleanup in bash?
Use trap 'cleanup' EXIT ERR INT TERM. Define cleanup() to remove temp files, kill child processes, release locks. trap ensures it runs even on crash or Ctrl+C.
What is the difference between `$@` and `$*`?
"$@" expands to separate quoted arguments ("arg1" "arg2"). "$*" joins with first char of IFS ("arg1 arg2"). Use "$@" almost always.
How do you create and use arrays in bash?
arr=(one two three) — declare. ${arr[0]} — first element. ${arr[@]} — all elements. ${#arr[@]} — length. arr+=("four") — append.
How do you parse command-line arguments?
Use getopts for short flags (while getopts "f:v" opt; do case $opt in ...), or case $1 in for positional. For complex CLI consider argparse (Python) or a proper framework.
What is a subshell and when is it created?
A separate process copy of the shell. Created by ( ... ), $(), pipelines, background &. Changes to variables/environment don't propagate back to parent. 🎯 This is why while read in a pipeline loses variables.
How do you make a script robust against missing files/empty output?
Check existence: [[ -f $file ]]. Check empty: [[ -s $file ]]. Use default: var=${1:-default}. Quote variables: "$var".
How do you make a script run periodically without cron?
Use a systemd timer unit (.timer + .service) — handles logging, dependencies, accuracy, and random delay (RandomizedDelaySec=). More robust than cron.