← Back to Index

Bash Reference

0. Basics

0.1 Hello World

#!/bin/bash
# echo prints strings to STDOUT and appends a newline by default
echo "Hello, World!"
TERMINAL OUTPUT
Hello, World!

0.2 Building & Running

Bash scripts are interpreted. Execute them directly by setting permissions or via the bash interpreter.

# Make the script executable
chmod +x script.sh
# Run the script directly
./script.sh

# Or run using the bash command
bash script.sh
TERMINAL OUTPUT
Hello, World!

0.3 Comments

# Single-line comment for brief notes and annotations
TERMINAL OUTPUT
(No output)

0.4 Imports

# Source a file to include its variables and functions in the current shell
source config.sh
# Shorthand for source
. config.sh
TERMINAL OUTPUT
(No output)

0.5 Exit Codes

# Terminate the script with a status code
# 0 for success, 1-255 for various error states
exit 1 
TERMINAL OUTPUT
(Process exits with status 1)

0.6 Error Handling

# Exit the script immediately if any command returns a non-zero exit code
set -e

# Define a trap to execute code when an error occurs
trap 'echo "Error on line $LINENO"' ERR
TERMINAL OUTPUT
(No output)

1. Environment, Variables & Time

1.1 Variable Declaration

Note: No spaces are allowed around the assignment operator =.

x="Value"         # Standard string variable
readonly PI=3.14  # Immutable constant
declare -i num=5  # Explicit integer-type variable
TERMINAL OUTPUT
(No output)

1.2 Integer Types & Limits

Bash handles 64-bit signed integers in arithmetic contexts (( )).

# Print the maximum value for a 64-bit signed integer
echo $((9223372036854775807))
TERMINAL OUTPUT
9223372036854775807

1.3 Casting

Explicit casting can be achieved via declare.

declare -i x="10"
# Arithmetic addition (result is 15, not string "105")
x+="5" 
echo $x
TERMINAL OUTPUT
15

1.4 Environment Variables

# Make a variable available to child processes
export API_KEY="secret"
# Access system environment variables
echo $PATH
TERMINAL OUTPUT
/usr/local/bin:/usr/bin:/bin (example)

1.5 Time Measurement & Formatting

# Measure elapsed time in seconds using the built-in SECONDS variable
start=$SECONDS
sleep 1
elapsed=$((SECONDS - start))

# Display current system date and time in custom formats
date +"%Y-%m-%d %H:%M:%S"
# Display current date in UTC ISO 8601 format
date -u +"%Y-%m-%dT%H:%M:%SZ" 
TERMINAL OUTPUT
2024-05-16 12:00:00 (example)
2024-05-16T12:00:00Z (example)

2. Operators & Regex

2.1 Arithmetic & Logic

Use (( )) for mathematical operations. Bash only supports integer math.

val=$((10 / 3)) # Result: 3 (integer truncation)
res=$((10 % 3)) # Result: 1 (remainder)
((x++))         # Post-increment variable x
TERMINAL OUTPUT
(No output)

2.2 Regex & Pattern Matching

Native regex matching available in [[ ]] blocks using the =~ operator.

text="Price: $100"
# Match '$' followed by digits
if [[ $text =~ \$([0-9]+) ]]; then
    # BASH_REMATCH array contains match results
    echo ${BASH_REMATCH[1]} 
fi
TERMINAL OUTPUT
100

3. Argument Parsing

3.1 Argument Parsing

The getopts built-in handles basic flag parsing.

# Define expected flags: v (no value), o (requires value indicated by :)
while getopts "vo:" opt; do
    case "$opt" in
        v) verbose=1 ;;
        o) output=$OPTARG ;; # OPTARG contains the flag's value
    esac
done
# Shift positional arguments to remove processed flags
shift $((OPTIND-1)) 
TERMINAL OUTPUT
(No output)

4. Functions & Memory

4.1 Declaration & Returns

# Define a function
add() {
    local a=$1 # Access parameters via $1, $2, etc.
    local b=$2
    # Return value by echoing to STDOUT
    echo $((a + b)) 
}

# Capture function output using command substitution
result=$(add 10 20)
echo $result
TERMINAL OUTPUT
30

4.2 References & Pointers

Available since Bash 4.3 using the nameref attribute (-n).

increment() {
    # 'ref' becomes a reference to the variable name passed as $1
    local -n ref=$1 
    ((ref++))
}

val=10
increment val # Pass the variable name, not the value
echo $val
TERMINAL OUTPUT
11

5. Control Flow

5.1 Conditionals (If/Else)

# Standard if/elif/else
# [ ] is a synonym for 'test'
x=10
if [ $x -gt 10 ]; then
    echo "Greater"
elif [ $x -eq 10 ]; then
    echo "Equal"
else
    echo "Lesser"
fi

# Truthiness: 0 indicates success (true)
if true; then echo "True"; fi

# String/File checks
if [ -z "" ]; then echo "Empty"; fi
TERMINAL OUTPUT
Equal
True
Empty

5.2 Switch / Case

val="stop"
case "$val" in
    "start") echo "Starting..." ;;
    "stop")  echo "Stopping..." ;;
    *)       echo "Unknown" ;; # Default case
esac
TERMINAL OUTPUT
Stopping...

5.3 Basic Loops (While/For)

# Standard for-in loop over a range
for i in {0..2}; do echo -n "$i"; done

x=0
# while loop using conditional expression
while [ $x -lt 3 ]; do
    echo -n "$x"
    ((x++))
done
TERMINAL OUTPUT
012012

5.4 Breaking & Continue

for x in {1..5}; do
    if [ $x -eq 2 ]; then continue; fi # Skip current iteration
    if [ $x -eq 4 ]; then break; fi    # Exit loop
    echo -n "$x"
done
TERMINAL OUTPUT
13

5.5 Iterating Collections

# Iterate over elements of an indexed array
list=("a" "b")
for val in "${list[@]}"; do echo -n "$val"; done

# Iterate over keys of an associative array
declare -A map=(["id"]="42")
for k in "${!map[@]}"; do 
    echo -n " $k:${map[$k]}"
done
TERMINAL OUTPUT
ab id:42

6. Strings & Files

6.1 String Manipulation

s="hello world"
echo ${#s}           # Get string length (11)
echo ${s:0:5}        # Extract substring from index 0, length 5 ("hello")
echo ${s/world/bash} # Replace first occurrence of "world" with "bash"
TERMINAL OUTPUT
11
hello
hello bash

6.2 Path Joining

In Bash, path segments are typically concatenated using the / character.

path="/usr/local"
# Construct full path by concatenation
full="$path/bin"
echo $full
TERMINAL OUTPUT
/usr/local/bin

6.3 Streaming I/O (Chunks)

# Read file line by line using the read command
while read -r line; do
    echo "Line: $line"
done < data.txt
TERMINAL OUTPUT
(Output depends on data.txt content)

6.4 Read to Memory

# Use command substitution with file redirection to read entire file content
content=$(<file.txt)
TERMINAL OUTPUT
(No output)

7. Binary & Bitwise

7.1 Allocation & Packing

Bash does not support native binary packing. Use printf or external tools like xxd.

# Use printf to output raw bytes (e.g., ASCII/Hex)
printf '\x42\x00'
TERMINAL OUTPUT
B (followed by a null byte)

7.2 Bitwise Operations

res=$((0b1010 & 0b1100)) # Bitwise AND
res=$((0b1010 | 0b1100)) # Bitwise OR
res=$((0b1010 ^ 0b1100)) # Bitwise XOR
res=$((~0b1010))         # Bitwise NOT (complement)
res=$((0b0001 << 2))     # Bitwise Shift Left (0b0100)
TERMINAL OUTPUT
(No output)

7.3 Hex Conversion

# Format integer as a 2-digit hex string
printf '%02x\n' 255 
TERMINAL OUTPUT
ff

8. Collections & JSON

8.1 Lists, Maps & Sets

# Indexed Array (List)
l=(1 2); l+=(3) 

# Associative Array (Map) - Requires Bash 4+
declare -A m=(["k"]="v")

# Set behavior achieved using keys of an associative array
declare -A s; s["unique_key"]=1
TERMINAL OUTPUT
(No output)

8.2 JSON Parsing

Bash requires external tools like jq for robust JSON processing.

# Perform floating point math using bc
echo "scale=2; 10/3" | bc 

# Extract a value from JSON using jq
echo '{"id":42}' | jq '.id' 

# String replacement using sed
echo "fox" | sed 's/fox/cat/' 
TERMINAL OUTPUT
3.33
42
cat

9. Systems & Networking

9.1 TCP Server & Client

Using Bash’s built-in /dev/tcp virtual filesystem (if enabled).

# Open a TCP connection to port 80 of a remote host
exec 3<>/dev/tcp/example.com/80
# Send an HTTP request
echo -e "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n" >&3
# Read the first line of the response
head -n 1 <&3
# Close the file descriptor
exec 3>&-
TERMINAL OUTPUT
HTTP/1.1 200 OK (example)

9.2 UDP Server & Client

# Send a UDP datagram to a local port
echo "data" > /dev/udp/127.0.0.1/8080
TERMINAL OUTPUT
(No output)

9.3 Concurrency

# Execute a command in a subshell in the background
(sleep 1; echo "Task Done") &
# Store the process ID of the last background command
pid=$!
# Wait for the background process to complete
wait $pid
TERMINAL OUTPUT
Task Done

9.4 SQLite

# Execute an SQL command against an in-memory database using the sqlite3 CLI
sqlite3 :memory: "SELECT 42;"
TERMINAL OUTPUT
42