Learn Shell Script by Examples
Bash 5.xShell scripting is a computer program designed to be run by the Unix shell, a command-line interpreter. It is essential for automating system administration tasks, file manipulation, and program execution.
These examples cover the fundamental building blocks of shell scripting in Bash, from variable manipulation and control structures to input/output redirection and pipelines.
Variables
Master Bash variable handling with this sample code demonstrating assignment syntax without spaces, variable expansion using dollar sign, readonly constants, the unset command, and export for creating environment variables accessible to child processes.
Quoting Rules
Understanding shell quoting mechanisms with this code example covering double quotes for variable expansion, single quotes for literal strings, escaping special characters with backslash, and proper quoting to handle filenames containing spaces.
Command Substitution
Capturing command output with this sample code showing the modern dollar-parentheses syntax, deprecated backtick notation for backward compatibility, nested command substitution, and using captured output in loops and variable assignments.
Arithmetic Expansion
Performing integer mathematics in Bash with this code example demonstrating the double-parentheses syntax for arithmetic operations, C-style increment and decrement operators, compound assignment operators, and numeric comparisons in conditional statements.
Conditionals
Implementing decision logic with this sample code demonstrating if-else statements using the test command, integer comparison operators like -ge and -lt, string equality checks, file existence tests, and case statements for pattern matching.
Loops
Iterating through data with this code example covering for loops over lists and C-style numeric ranges, while loops that execute based on conditions, until loops that run until conditions become true, and loop control with break and continue.
Functions
Creating reusable code blocks with this sample code showing function definition syntax, accessing arguments via positional parameters, local variable scope, return statements for exit status, and capturing function output using command substitution.
Positional Parameters
Accessing script arguments with this code example demonstrating special variables like $0 for script name, $1-$9 for arguments, $# for argument count, $@ for all arguments, the shift command, and $? for exit status.
Pipelines
Connecting commands together with this sample code showing the pipe operator for chaining utilities, combining grep, sort, and head for data processing, using xargs to convert stdin to arguments, and set -o pipefail for robust error handling.
Redirection
Controlling input and output streams with this code example demonstrating stdout redirection with > and >>, stderr redirection with 2>, combining streams with &>, input redirection with <, and here documents for multi-line input.

