NANDHOO.

Chapter 13: Advanced Scripting

Writing scripts that work in ideal conditions is easy. Writing scripts that handle edge cases, recover from errors, and manipulate data efficiently requires mastery of advanced Bash features. This chapter covers the "Pro" tools of shell scripting.

I. Advanced Variable Expansion

Bash provides powerful syntax for manipulating strings and handling empty variables without needing external tools like sed or awk.

1. Default Values

  • ${VAR:-default}: If VAR is unset or empty, use default.
  • ${VAR:?error}: If VAR is unset or empty, exit the script with an error message.

2. String Manipulation

PATH_VAR="/usr/local/bin/python3"

# Get the extension (Everything after last dot)
echo "${PATH_VAR##*.}" # Output: 3

# Remove the path (Everything before last slash)
echo "${PATH_VAR##*/}" # Output: python3

# Search and Replace
echo "${PATH_VAR//python/ruby}" # Output: /usr/local/bin/ruby3

II. Error Handling and "Strict Mode"

By default, Bash is very "loose." It won't stop if a command fails. Professional scripts use the following header:

#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
  • -e: Exit immediately if any command returns a non-zero status.
  • -u: Exit if you try to use an uninitialized variable.
  • -o pipefail: If any command in a pipe fails, the whole pipe returns a failure code.

III. Signal Trapping (Graceful Cleanup)

A robust script should clean up after itself, even if it is interrupted by the user (Ctrl+C).

SIGINT(Ctrl+C)TRAP MECHANISM1. Catch Signal2. Run cleanup()3. Exit scriptCLEANUP(Delete Temps)

cleanup() {
    echo "Shutting down..."
    rm -rf "$TEMP_DIR"
    exit 0
}

trap cleanup SIGINT SIGTERM

IV. Subshells: Process Isolation

Sometimes you want to run a group of commands without changing the environment of your main script (e.g., changing directories). Use parentheses ( ... ) to create a subshell.

# Main script starts in /home/user
(
    cd /tmp
    touch test_file
    # Directory change only affects this block
)
# Main script is still in /home/user

V. Advanced Arithmetic with bc

Bash only supports integer math. If you need floating-point precision (decimals), pipe your expression to bc (An arbitrary precision calculator).

# Scale=2 sets decimal places
VAL=$(echo "scale=2; 10 / 3" | bc)
echo "Result: $VAL" # Output: 3.33

VI. Debugging with set -x

If a script is failing and you can't see why, add set -x to the top. This "Trace Mode" prints every command and its expanded variables before execution.

In the next chapter, we'll shift gears and look at Windows Batch Scripting for cross-platform environments.