Shell Scripting, Bash & CLI Automation Master Interview Bank
Bash shell scripting, POSIX standards, file descriptors (stdin/stdout/stderr), pipes, signal trapping, stream editing with sed/awk, and process substitution.
Curriculum Roadmap & Learning Path
3 StagesPart 1: Basic & Foundational Concepts (Junior / Entry-Level)
10 QuestionsWhat is the Shebang (`#!/usr/bin/env bash`) line and why is it used?
The shebang (#!) is the very first line of an executable script: Tells the Linux kernel which interpreter binary to launch to execute the script • !/bin/bash: Hardcodes the binary path (may fail on systems where Bash lives in /usr/local/bin).
What are the quoting rules in Bash (Double Quotes `""` vs Single Quotes `''`)?
The most common source of bugs in shell scripting: Single Quotes ('...'): Literal interpretation • Double Quotes ("..."): Weak quoting • Rule: Always wrap variables in double quotes ("$filepath") to prevent word splitting and globbing on filenames containing spaces!.
What is the difference between Command Substitution `$(command)` and Backticks `` `command` ``?
Both execute a shell command and capture its standard output: $(command) (Modern Standard): Readable, supports clean arbitrary nesting without escaping • Backticks command (Legacy): Difficult to read and requires awkward escaping when nesting.
What are Exit Codes (`$?`) and how does Bash indicate success or failure?
Every Linux command returns an integer exit status (0 to 255) upon termination: 0: Success / No errors • Non-zero (1 to 255): Failure or error (e.g. 1 = General error, 2 = Misuse of shell builtins, 127 = Command not found) • The special variable $?.
What are the special command-line argument variables (`$0`, `$1`, `$#`, `$@`, `$*`)?
When running ./deploy.sh staging v1.2: 0: The name/path of the executing script itself (./deploy.sh) • 1, 2, 3: Positional arguments (1 = "staging", 2 = "v1.2") • #: Total count of positional arguments passed (2).
What is the difference between `[[ ... ]]` and `[ ... ]` (test command)?
[ .. • [[ .. • Does not undergo word splitting or glob expansion • Supports regular expression matching via the =~ operator: [[ "$email" =~ ^[A-Z0-9._%+-]+@ ]].
What are the primary File Test Operators in Bash?
Used in conditional checks to inspect files and directories: [[ -f "path" ]]: True if path exists and is a regular file • [[ -d "path" ]]: True if path exists and is a directory • [[ -e "path" ]]: True if path exists (any type: file, dir, socket, symlink) • [[ -s "path" ]]: True if file exists and has size greater than zero (not empty).
How do you safely read a file line-by-line in Bash?
Never use for line in $(cat file.txt) (it splits words by spaces and strips empty lines!).: The Universal Safe Pattern.
What are the basic Stream Redirections (`>`, `>>`, `2>`, `2>&1`)?
Linux processes have three standard streams: File Descriptor 0 (stdin), 1 (stdout), and 2 (stderr): : Overwrites standard output to a file (echo "hello" > file.txt) • : Appends standard output to a file • 2>: Redirects standard error only (ls /root 2> errors.log).
What is a Here Document (`<<EOF`) and Here String (`<<<`)?
Here Document (<<EOF): Multi-line block of text passed directly into the standard input of a command.
Part 2: Core Architecture & Implementation (Mid-Level)
10 QuestionsWhat does `set -euo pipefail` do and why should every production script start with it?
The gold standard for defensive shell scripting: e (errexit): Exits immediately if any command exits with a non-zero status • u (nounset): Treats unset/uninitialized variables as an error and exits immediately (prevents rm -rf "$UNSET_VAR/*" wiping out /).
What is Parameter Expansion in Bash (`${var:-default}`, `${var//search/replace}`)?
Manipulates variables directly in memory without launching external processes (sed/awk): Default Value: {VAR:-"fallback"} (uses fallback if VAR is unset or empty) • Assign Default: {VAR:="default"} (assigns default to variable if empty) • Error if Unset: {VAR:?"Variable is required!"} (aborts script if empty).
How do you parse command-line flags and options using `getopts`?
getopts is a built-in utility for parsing short CLI options (e.g. ./script.sh -f input.txt -v).
What are Signals and the `trap` command in Bash?
trap catches OS signals sent to the script process and executes a cleanup function before exit: Signals: SIGINT (Ctrl+C), SIGTERM (kill), EXIT (normal or abnormal script exit) • Guarantees that temporary files and lockfiles are deleted even if the script is interrupted!.
How does Process Substitution `<(...)` work?
Process substitution allows the output of a command to appear as a temporary file path (/dev/fd/63): Instead of creating temporary files on disk to compare outputs.
What is a Subshell in Bash and how do parentheses `(...)` differ from braces `{...}`?
Parentheses ( .. • Braces { ...; }: Executes commands inside the current shell environment.
How do you manipulate Arrays and Associative Arrays in Bash?
Indexed Array • Associative Array (Key-Value Dictionary, Bash 4+).
What are Functions and the `local` keyword in Bash?
Functions group reusable blocks of commands: The local Keyword: By default, all variables in Bash are global! • Always declare variables inside functions with local.
How do you implement a File Lock (Mutex) to prevent concurrent script execution?
Use the Linux utility flock: Creates an advisory file lock on a dedicated file descriptor.
What is the difference between `source ./script.sh` (or `. ./script.sh`) and `./script.sh`?
./script.sh: Launches a new separate child Bash process • source ./script.sh (or.
Part 3: Advanced Text Processing & Production Internals (Senior / Lead)
30 QuestionsHow do you use `grep` with Extended Regular Expressions (`-E`) and inverse matching?
grep searches text streams for matching patterns: E (or egrep): Enables extended regular expressions (+, ?, , ()) • v: Inverts match (returns lines that do NOT match) • i: Case-insensitive • o: Prints only the matched parts of a line, not the entire line.
How does `sed` (Stream Editor) work for find & replace in files?
sed performs basic text transformations on an input stream or file: Syntax: sed 's/search_pattern/replacement/flags' • Flags: g (global - replace all occurrences per line), i (case-insensitive) • In-Place Editing (-i): Modifies the file directly on disk (sed -i 's/localhost/10.0.0.1/g' config.env).
What are `awk` fundamentals (Pattern-Action, `$1`, `$2`, `NF`, `NR`)?
awk is a complete programming language designed for processing column-oriented structured text: Line parsing: Splits lines by whitespace (or custom delimiter -F',') • 0: Entire line • 1, 2, 3: Column 1, Column 2, Column 3 • NF: Number of Fields (columns) in the current line ($NF is the last column!).
How do you use `BEGIN` and `END` blocks in `awk` for data aggregation?
BEGIN { .. • Pattern Action { .. • END { .
What causes the Subshell Variable Loss trap in `while` loops with pipes?
The classic Bash pitfall.
What is `xargs` and how does `-P` enable parallel execution?
xargs builds and executes commands from standard input: Parallel Processing (-P N): Spawns N concurrent worker processes.
How do you create temporary files securely with `mktemp`?
Never hardcode /tmp/mytempfile.txt (vulnerable to symlink race condition attacks!): Use mktemp: Generates a cryptographically random, secure filename with strict 0600 permissions (only accessible by the current user).
How does Job Control work in Bash (`&`, `nohup`, `jobs`, `fg`, `bg`, `disown`)?
&: Runs command in the background • nohup command &: Protects background process from receiving SIGHUP when the terminal disconnects • jobs: Lists background jobs in the current shell • fg %1: Brings job 1 to the foreground.
What is the difference between `exec command` and running `command`?
Running command: Forks a child process; shell waits for it to finish • exec command: Replaces the current shell process entirely with the new executable! • PID remains identical • When command terminates, the process terminates; no subsequent lines of the script will ever run!.
How do you implement Exponential Backoff and Retries in Bash?
Exponential backoff in Bash retries failing operations in a loop, doubling the sleep interval between attempts to avoid overwhelming downstream services. #### Code Example.
What is the `eval` command and why is it considered dangerous?
eval string parses and evaluates string arguments as executable shell commands: Security Vulnerability: If untrusted user input is passed to eval, an attacker can inject arbitrary commands (eval "ls userinput" where • Almost always replaceable with Arrays, Parameter Expansion, or Indirect Variable References ({!var}).
How do you debug a Bash script (`set -x`, `bash -n`, `trap DEBUG`)?
Syntax Check without Execution: bash -n script.sh (validates syntax errors) • Execution Tracing: bash -x script.sh (prints every command and its expanded arguments prefixed with +) • ShellCheck: Run shellcheck script.sh (static linter that detects hundreds of security risks, syntax bugs, and quoting errors).
What is the Internal Field Separator (`$IFS`)?
$IFS determines how Bash recognizes word boundaries during word splitting: Default value: `` • You can temporarily customize it to parse CSV or colon-separated strings.
How do you measure script execution time in milliseconds?
In Bash 5.0+, use the built-in variable $EPOCHREALTIME (returns microsecond-precision epoch timestamp).
When should you stop using Bash and switch to Python or Go?
Stay with Bash: Lightweight automation scripts under 200 lines, gluing Unix command-line utilities together (grep, sed, docker, git), cron jobs • Switch to Python / Go • Complex data structures (nested maps, lists of objects) • Heavy JSON/YAML parsing and API client integrations.
Parameter Expansion Tricks: String replacement, default fallbacks (`$:-`, `$:=`, `$:?`), substring slicing, and length.
Bash parameter expansion performs fast string manipulation directly inside the shell process without spawning slow subshells (sed or awk).
Associative Arrays (Hash Maps) vs Indexed Arrays in Bash: Declaration, iteration, and pitfalls.
Bash 4.0+ supports key-value hash maps via declare -A.
File Locking in Bash with `flock`: Preventing multiple simultaneous cron executions.
When a cron job takes longer to run than its execution frequency (e.g., a 10-minute backup scheduled every 5 minutes), overlapping instances will thrash CPU and corrupt files. flock uses kernel-level advisory file locking to ensure strictly one instance runs at any given time.
Process Substitution (`<()`, `>()`) vs Named Pipes (`mkfifo`): Syntax and use cases.
Process substitution allows the standard output or input of a command to appear as a temporary file descriptor (/dev/fd/63), avoiding intermediate temporary files on disk.
Here Documents (`<<EOF`), Quoted Here Docs (`<<'EOF'`), and Here Strings (`<<<`).
Unquoted HereDoc (<<EOF): Evaluates variables (VAR), command substitutions ((date)), and arithmetic before feeding into stdin • Quoted HereDoc (<<'EOF'): Treats all content as raw literal text without variable expansion • Here String (<<<): Feeds a single string variable directly into stdin without needing echo .
Signal Trapping (`trap`) for graceful cleanup of temporary files on `EXIT`, `INT`, and `TERM`.
Scripts frequently create temporary files in /tmp. If a user presses Ctrl+C (SIGINT) or the process is killed (SIGTERM), orphaned files clutter the disk. The trap command registers guaranteed cleanup handlers.
Defensive Bash Boilerplate: `set -euo pipefail` and custom error trap handlers.
By default, Bash happily continues executing subsequent commands even if an earlier command threw a fatal error! Production scripts must start with the Strict Mode prelude.
Working with JSON in Bash: Best practices using `jq` vs fragile regex parsing.
Never parse JSON with grep, sed, or awk — multiline strings, escaped quotes, and nested arrays break regex immediately. Always use jq.
Parsing Command-Line Options with `getopts`: Handling flags (`-f`), arguments (`-o value`), and help output.
getopts is Bash's built-in POSIX option parser for handling short flags.
Subshells `(...)` vs Command Grouping `{ ...; }`: Memory isolation and environment variable scope.
Subshell ( cd /tmp && ls ): Spawns a child process • Command Grouping { cd /tmp; ls; }: Executes within the current shell process.
Concurrency and Parallel Job Processing in Bash: Background jobs (`&`), `wait`, and `xargs -P`.
Executing independent tasks in parallel accelerates batch processing.
TCP Sockets in Bash: Native network reads/writes using `/dev/tcp/host/port` without curl or netcat.
Bash includes built-in TCP/UDP socket abstraction via virtual paths.
Security in Bash: Preventing command injection (`eval` risks) and safe variable quoting rules.
Never use eval with user input: eval "cmd userinput" allows an attacker to pass ; rm -rf / or (maliciouscommand) • Always Quote Variables: Use "VAR" instead of VAR • Use printf %q: Sanitizes and safely escapes arbitrary strings for reuse in shell commands.
Testing Bash Scripts with BATS (Bash Automated Testing System): Assertions and mocks.
BATS is an automated testing framework for Bash scripts providing unit test structures.
Building Interactive CLI Prompts: Colored terminal output, menus (`select`), and silent input (`read -s`).
Creating polished interactive developer tools.