Basic Script
#!/bin/bashselects the interpreter.if-else-fihandles conditional execution.echoprints output.$#,$0, and$1are special variables.domain=$1stores the first user argument.
Shebang
The shebang is the first line of a script and starts with#!. It tells the
system which interpreter should run the file.
Conditionals
Useif, elif, else, and fi to branch based on conditions.
Arguments and Variables
Bash supports positional arguments directly.$0is the script name.$1to$9are the first nine positional arguments.$#is the number of arguments.
Special Variables
Special variables use the Internal Field Separator (IFS) to split arguments.
Variables
Assignments do not use$, and there must be no spaces around =.
local.
Arrays
Arrays store multiple values under one variable name, indexed from0.
Arithmetic
Use arithmetic expansion$((...)) and increment/decrement operators for math.
${#variable} returns string length:
Input and Output
Input Control
Useread when the script should pause for user input.
Output Control
Usetee when you want to both display output and save it to a file.
-a appends instead of overwriting.
Flow Control - Branches
Branches let the script choose one path over another. In Bash, the main branch constructs areif-else and case.
Case Statements
case compares one expression against exact patterns.
Functions
Functions keep scripts shorter and easier to reuse. Define them before the first call because Bash reads from top to bottom.Parameter Passing
Functions use their own positional parameters, just like scripts.Return Values
Functions return status codes, and$? reads the last one.
Flow Control - Loops
Loops repeat work until input is exhausted or a condition changes.forloops iterate over items.whileloops run while a condition is true.untilloops run while a condition is false.
For Loops
While Loops
while loops need a counter or changing condition so they do not run forever.
continue skips to the next iteration and break exits the loop.
Until Loops
until is the inverse of while: it runs until the condition becomes true.
Comparison Operators
Bash operators are usually grouped into string, integer, file, and logical checks.String Operators
Quote strings like
"$1" to avoid parsing issues.
< and > string comparisons work inside [[ ... ]].
Integer Operators
File Operators
Boolean and Logical Operators
Use[[ ... ]] for boolean-style checks.
Debugging
Bash debugging is usually done with-x and -v.
bash -x script.shshows each command as it executes.bash -x -v script.shalso shows the code as Bash reads it.