AI Generate Shell docs instantly

Shell Cheat Sheet

Quick reference guide with copy-paste ready code snippets

Try DocuWriter Free

Getting Started

5 snippets

Basic shell scripting fundamentals

Hello World

#!/bin/bash
echo "Hello, World!"

Shebang Variants

#!/bin/bash   # Bash
#!/bin/sh     # POSIX shell
#!/usr/bin/env bash  # Portable

Comments

# Single line comment

: '
Multi-line comment
using colon operator
'

Make Executable

chmod +x script.sh
./script.sh

Run Without Execute Permission

bash script.sh
sh script.sh

Variables

6 snippets

Variable declaration and usage

Variable Assignment

name="John"          # No spaces around =
count=42
path="/usr/local/bin"

Variable Usage

echo $name           # Basic usage
echo "${name}"       # Explicit braces
echo "Hello, $name"  # In strings

Command Substitution

today=$(date +%Y-%m-%d)
files=$(ls -l)
count=$(wc -l < file.txt)

Read User Input

read -p "Enter name: " username
read -sp "Password: " password  # Silent
read -t 5 -p "Quick: " answer   # Timeout

Environment Variables

export PATH="/usr/local/bin:$PATH"
export DB_HOST="localhost"
env | grep PATH  # View all

Special Variables

$0  # Script name
$1, $2  # Arguments
$#  # Argument count
$@  # All arguments
$?  # Last exit status
$$  # Process ID

Operators & Comparisons

5 snippets

Arithmetic and test operators

Arithmetic

result=$((5 + 3))
count=$((count + 1))
value=$((10 * 2 - 5))

String Comparison

if [ "$str1" = "$str2" ]; then
  echo "Equal"
fi

if [ "$str1" != "$str2" ]; then
  echo "Not equal"
fi

Integer Comparison

if [ $a -eq $b ]; then echo "Equal"; fi
if [ $a -ne $b ]; then echo "Not equal"; fi
if [ $a -gt $b ]; then echo "Greater"; fi
if [ $a -lt $b ]; then echo "Less"; fi

File Tests

[ -f file.txt ]  # File exists
[ -d /path ]     # Directory exists
[ -r file ]      # Readable
[ -w file ]      # Writable
[ -x file ]      # Executable

Logical Operators

if [ $a -gt 0 ] && [ $b -gt 0 ]; then
  echo "Both positive"
fi

if [ $a -gt 0 ] || [ $b -gt 0 ]; then
  echo "At least one positive"
fi

Tired of looking up syntax?

DocuWriter.ai generates documentation and explains code using AI.

Try Free

Control Flow

5 snippets

Conditional statements

If Statement

if [ $age -ge 18 ]; then
  echo "Adult"
fi

If-Else

if [ $score -ge 60 ]; then
  echo "Pass"
else
  echo "Fail"
fi

If-Elif-Else

if [ $grade -ge 90 ]; then
  echo "A"
elif [ $grade -ge 80 ]; then
  echo "B"
else
  echo "C"
fi

Case Statement

case $fruit in
  apple)
    echo "Red"
    ;;
  banana)
    echo "Yellow"
    ;;
  *)
    echo "Unknown"
    ;;
esac

Test Syntax [[ ]]

if [[ $name == "John" ]]; then
  echo "Hello John"
fi

if [[ $str =~ ^[0-9]+$ ]]; then
  echo "Number"
fi

Loops

7 snippets

Iteration constructs

For Loop (List)

for item in apple banana cherry; do
  echo $item
done

For Loop (Range)

for i in {1..10}; do
  echo "Number: $i"
done

For Loop (C-style)

for ((i=0; i<10; i++)); do
  echo $i
done

While Loop

count=0
while [ $count -lt 5 ]; do
  echo $count
  count=$((count + 1))
done

Until Loop

count=0
until [ $count -ge 5 ]; do
  echo $count
  count=$((count + 1))
done

Loop Over Files

for file in *.txt; do
  echo "Processing: $file"
  wc -l "$file"
done

Read Lines from File

while IFS= read -r line; do
  echo "Line: $line"
done < file.txt

Functions

4 snippets

Reusable code blocks

Function Definition

greet() {
  echo "Hello, $1"
}

greet "World"

Function with Return

add() {
  local sum=$(($1 + $2))
  echo $sum
}

result=$(add 5 3)
echo "Result: $result"

Function with Status

check_file() {
  if [ -f "$1" ]; then
    return 0  # Success
  else
    return 1  # Failure
  fi
}

if check_file "test.txt"; then
  echo "File exists"
fi

Local Variables

calculate() {
  local x=10
  local y=20
  echo $((x + y))
}

Arrays

6 snippets

Working with arrays

Array Declaration

fruits=("apple" "banana" "cherry")
numbers=(1 2 3 4 5)

Access Elements

echo ${fruits[0]}     # First element
echo ${fruits[2]}     # Third element
echo ${fruits[-1]}    # Last element

Array Length

echo ${#fruits[@]}    # Number of elements
echo ${#fruits[0]}    # Length of first element

Loop Through Array

for fruit in "${fruits[@]}"; do
  echo $fruit
done

Add/Remove Elements

fruits+=("orange")       # Append
unset fruits[1]          # Remove element

Array Slicing

echo ${fruits[@]:1:2}   # Elements 1-2
echo ${fruits[@]:2}     # From index 2 to end

File I/O & Redirection

6 snippets

Reading and writing files

Write to File

echo "Hello" > file.txt       # Overwrite
echo "World" >> file.txt      # Append

Read from File

content=$(cat file.txt)
while read line; do
  echo $line
done < file.txt

Here Document

cat <<EOF > config.txt
Name: John
Age: 30
EOF

Redirect Stderr

command 2> error.log          # Stderr to file
command 2>&1                  # Stderr to stdout
command &> output.log         # Both to file

Pipe Output

ls -l | grep ".txt"
cat file.txt | wc -l
ps aux | grep nginx

Test File Existence

if [ -f "file.txt" ]; then
  cat file.txt
else
  echo "File not found"
fi

More Cheat Sheets

FAQ

Frequently asked questions

What is a Shell cheat sheet?

A Shell cheat sheet is a quick reference guide containing the most commonly used syntax, functions, and patterns in Shell. It helps developers quickly look up syntax without searching through documentation.

How do I learn Shell quickly?

Start with the basics: variables, control flow, and functions. Use this cheat sheet as a reference while practicing. For faster learning, try DocuWriter.ai to automatically explain code and generate documentation as you learn.

What are the most important Shell concepts?

Key Shell concepts include variables and data types, control flow (if/else, loops), functions, error handling, and working with data structures like arrays and objects/dictionaries.

How can I document my Shell code?

Use inline comments for complex logic, docstrings for functions and classes, and README files for projects. DocuWriter.ai can automatically generate professional documentation from your Shell code using AI.

Code Conversion Tools

Convert Shell to Other Languages

Easily translate your Shell code to other programming languages with our AI-powered converters

Related resources

Stop memorizing. Start shipping.

Generate Shell Docs with AI

DocuWriter.ai automatically generates comments, docstrings, and README files for your code.

Auto-generate comments
Create README files
Explain complex code
API documentation
Start Free - No Credit Card

Join 33,700+ developers saving hours every week