Shell Scripting Fundamentals
What are the essential components of a shell script? Explain variables, conditionals, and loops.
Shell scripts automate command sequences. Essential components: 1) Shebang (#!/bin/bash) - specifies interpreter. 2) Variables - store values, accessed with $. 3) Conditionals (if/elif/else) - control flow based on conditions. 4) Loops (for, while) - iterate over items or until condition. 5) Functions - reusable code blocks. 6) Exit codes - indicate success (0) or failure (non-zero). Always quote variables and use 'set -e' for error handling.
Shell scripting is the glue of DevOps - automating repetitive tasks, deployment scripts, cron jobs, and system administration. Bash is most common on Linux, but principles apply to other shells. Well-written scripts include error handling, logging, and are idempotent when possible.
Basic script structure
Functions and error handling
- Not quoting variables, causing word splitting issues
- Forgetting to handle error cases (missing 'set -e')
- Using 'rm -rf $VAR' without checking if VAR is set
- What does 'set -euo pipefail' do and why is it important?
- How do you pass arguments to a shell script?
- What is the difference between single and double quotes in bash?