Bash Scripting

0%
Scriptingbashscriptingsettrapfunctionsarraysgetopts

Bash Scripting

8 interactive questions

ScriptingQuestion
bashscriptingsettrapfunctionsarraysgetopts

What is `set -euo pipefail` and why use it?

Click to reveal answer
ScriptingAnswer

-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.

ScriptingQuestion
bashscriptingsettrapfunctionsarraysgetopts

How do you handle errors and cleanup in bash?

Click to reveal answer
ScriptingAnswer

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.

ScriptingQuestion
bashscriptingsettrapfunctionsarraysgetopts

What is the difference between `$@` and `$*`?

Click to reveal answer
ScriptingAnswer

"$@" expands to separate quoted arguments ("arg1" "arg2"). "$*" joins with first char of IFS ("arg1 arg2"). Use "$@" almost always.

ScriptingQuestion
bashscriptingsettrapfunctionsarraysgetopts

How do you create and use arrays in bash?

Click to reveal answer
ScriptingAnswer

arr=(one two three) — declare. ${arr[0]} — first element. ${arr[@]} — all elements. ${#arr[@]} — length. arr+=("four") — append.

ScriptingQuestion
bashscriptingsettrapfunctionsarraysgetopts

How do you parse command-line arguments?

Click to reveal answer
ScriptingAnswer

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.

ScriptingQuestion
bashscriptingsettrapfunctionsarraysgetopts

What is a subshell and when is it created?

Click to reveal answer
ScriptingAnswer

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.

ScriptingQuestion
bashscriptingsettrapfunctionsarraysgetopts

How do you make a script robust against missing files/empty output?

Click to reveal answer
ScriptingAnswer

Check existence: [[ -f $file ]]. Check empty: [[ -s $file ]]. Use default: var=${1:-default}. Quote variables: "$var".

ScriptingQuestion
bashscriptingsettrapfunctionsarraysgetopts

How do you make a script run periodically without cron?

Click to reveal answer
ScriptingAnswer

Use a systemd timer unit (.timer + .service) — handles logging, dependencies, accuracy, and random delay (RandomizedDelaySec=). More robust than cron.