Bash Scripting Cheatsheet — Variables, Loops, Functions

Write Bash scripts: variables, conditionals, loops, functions, arrays, string manipulation. With examples.

Script Basics

#!/bin/bash
# Shebang line — always first

set -euo pipefail  # Strict mode: exit on error, undefined vars, pipe failures

Variables

NAME="world"
echo "Hello, $NAME"          # String interpolation
echo "Path: ${HOME}/docs"    # Use braces for clarity
readonly PI=3.14              # Constant
TODAY=$(date +%Y-%m-%d)       # Command substitution

Conditionals

if [[ -f "file.txt" ]]; then
  echo "File exists"
elif [[ -d "dir" ]]; then
  echo "Directory exists"
else
  echo "Neither"
fi

# Common test operators
[[ -f file ]]    # File exists
[[ -d dir ]]     # Directory exists
[[ -z "$var" ]]  # String is empty
[[ -n "$var" ]]  # String is non-empty
[[ $a -eq $b ]]  # Integer equal
[[ $a == $b ]]   # String equal

Loops

# For loop
for file in *.txt; do
  echo "Processing $file"
done

# C-style for loop
for ((i=0; i<10; i++)); do
  echo $i
done

# While loop
while read -r line; do
  echo "$line"
done < input.txt

Functions

greet() {
  local name="$1"
  echo "Hello, $name"
  return 0
}

greet "World"

Arrays

arr=("one" "two" "three")
echo "${arr[0]}"       # First element
echo "${arr[@]}"       # All elements
echo "${#arr[@]}"      # Length
arr+=("four")           # Append

Useful Patterns

# Check if command exists
if command -v docker &>/dev/null; then
  echo "Docker installed"
fi

# Default value
${VAR:-default_value}

# Error handling
trap 'echo "Error on line $LINENO"; exit 1' ERR

Need These Tools as an API?

TextForge API offers 20+ developer toolkit endpoints. Free tier: 50 requests/day.

Try TextForge API Free →

Related Tools