Skip to main content

Basic Script

  • #!/bin/bash selects the interpreter.
  • if-else-fi handles conditional execution.
  • echo prints output.
  • $#, $0, and $1 are special variables.
  • domain=$1 stores 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.
Other common examples:

Conditionals

Use if, elif, else, and fi to branch based on conditions.

Arguments and Variables

Bash supports positional arguments directly.
  • $0 is the script name.
  • $1 to $9 are 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 =.
Bash treats variable content mostly as strings unless used in arithmetic. Variables are global by default unless declared with local.

Arrays

Arrays store multiple values under one variable name, indexed from 0.
Quoted values stay together as one array element:

Arithmetic

Use arithmetic expansion $((...)) and increment/decrement operators for math.
${#variable} returns string length:

Input and Output

Input Control

Use read when the script should pause for user input.

Output Control

Use tee 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 are if-else and case.

Case Statements

case compares one expression against exact patterns.
Example:

Functions

Functions keep scripts shorter and easier to reuse. Define them before the first call because Bash reads from top to bottom.
Example:

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.
  • for loops iterate over items.
  • while loops run while a condition is true.
  • until loops run while a condition is false.

For Loops

One-line form:

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.sh shows each command as it executes.
  • bash -x -v script.sh also shows the code as Bash reads it.