DEV Community

Lakh Bawa
Lakh Bawa

Posted on

Easy to follow Bash Scripting Cheatsheet

Bash scripting is essential if you do any kind of server management such as setting up a Linux server, setting up deployment, etc. You can write bash scripts/shell scripts to automate common tasks. I created this bash scripting cheatsheet that can provide you with fundamental knowledge about bash scripting

Basic Script Structure

#!/bin/bash
# Shebang line - tells the system to use bash interpreter

# Script header
SCRIPT_NAME="example_script"
VERSION="1.0"
AUTHOR="Your Name"
DATE=$(date +"%Y-%m-%d")
Enter fullscreen mode Exit fullscreen mode

Variables

# Variable Declaration
name="John Doe"
age=30

# Read-only Variables
readonly PI=3.14159

# Environment Variables
echo $HOME
echo $USER
echo $PATH

# Command Substitution
current_date=$(date)
files=$(ls)

# Default Values
var=${parameter:-default_value}  # Use default if parameter is unset or null
var=${parameter:=default_value}  # Assign default if parameter is unset or null
Enter fullscreen mode Exit fullscreen mode

Input and Output

# User Input
read -p "Enter your name: " username
read -sp "Enter password: " password  # Silent input

# Standard Output
echo "Hello, World!"
printf "Formatted output: %s is %d years old\n" "$name" "$age"

# Error Output
echo "Error message" >&2

# Redirecting Output
command > output.txt        # Overwrite
command >> output.txt       # Append
command 2> error.log        # Redirect stderr
command &> all_output.log   # Redirect both stdout and stderr
Enter fullscreen mode Exit fullscreen mode

Conditional Statements

# If-Else Statements
if [ condition ]; then
    # commands
elif [ another_condition ]; then
    # commands
else
    # commands
fi

# Comparison Operators
# Numeric Comparisons
[ $a -eq $b ]  # Equal
[ $a -ne $b ]  # Not Equal
[ $a -gt $b ]  # Greater Than
[ $a -lt $b ]  # Less Than
[ $a -ge $b ]  # Greater or Equal
[ $a -le $b ]  # Less or Equal

# String Comparisons
[ "$str1" = "$str2" ]   # Equal
[ "$str1" != "$str2" ]  # Not Equal
[ -z "$str" ]           # Zero length
[ -n "$str" ]           # Non-zero length

# File Condition Tests
[ -f file ]     # Regular file exists
[ -d directory ]# Directory exists
[ -r file ]     # File is readable
[ -w file ]     # File is writable
[ -x file ]     # File is executable
[ -e file ]     # File exists
Enter fullscreen mode Exit fullscreen mode

Loops

# For Loop
for variable in {1..5}; do
    echo $variable
done

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

# C-style For Loop
for (( i=0; i<5; i++ )); do
    echo $i
done

# While Loop
counter=0
while [ $counter -lt 5 ]; do
    echo $counter
    ((counter++))
done

# Until Loop
counter=0
until [ $counter -ge 5 ]; do
    echo $counter
    ((counter++))
done

# Break and Continue
while true; do
    # some condition
    break       # Exit loop
    continue    # Skip to next iteration
done
Enter fullscreen mode Exit fullscreen mode

Functions

# Function Definition
function greet() {
    local name=$1
    echo "Hello, $name!"
}

# Alternative Syntax
greet() {
    echo "Hello, $1!"
}

# Function with Return Value
calculate_sum() {
    return $(($1 + $2))
}

# Calling Functions
greet "Alice"
calculate_sum 5 3
echo $?  # Prints the return value
Enter fullscreen mode Exit fullscreen mode

Arrays

# Declaring Arrays
fruits=("Apple" "Banana" "Cherry")
numbers=(1 2 3 4 5)

# Access Array Elements
echo ${fruits[0]}
echo ${fruits[-1]}  # Last element

# All Array Elements
echo ${fruits[@]}
echo ${#fruits[@]}  # Array Length

# Modifying Arrays
fruits+=("Date")    # Append
unset fruits[1]     # Remove element
Enter fullscreen mode Exit fullscreen mode

String Manipulation

# Substring Extraction
str="Hello, World!"
echo ${str:0:5}     # Substring from index 0, length 5
echo ${str:7}       # Substring from index 7 to end

# String Length
echo ${#str}

# String Replacement
text="Hello, World!"
echo ${text/World/Universe}  # Replace first occurrence
echo ${text//o/0}            # Replace all occurrences

# Case Conversion
echo ${str^^}       # Uppercase
echo ${str,,}       # Lowercase
Enter fullscreen mode Exit fullscreen mode

Command-Line Arguments

# Accessing Arguments
echo $0         # Script name
echo $1         # First argument
echo $2         # Second argument
echo $#         # Number of arguments
echo $@         # All arguments

# Argument Processing
while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            display_help
            shift
            ;;
        -v|--version)
            echo "Version 1.0"
            shift
            ;;
        *)
            echo "Unknown option: $1"
            shift
            ;;
    esac
done
Enter fullscreen mode Exit fullscreen mode

Error Handling

# Exit Codes
exit 0    # Successful execution
exit 1    # Generic error

# Error Checking
command || { echo "Command failed"; exit 1; }

# Set Strict Mode
set -e  # Exit immediately on error
set -u  # Treat unset variables as error
set -o pipefail  # Fail on any command in a pipeline
Enter fullscreen mode Exit fullscreen mode

File Handling

# File Existence
if [ -f "file.txt" ]; then
    echo "File exists"
fi

# Reading Files
while IFS= read -r line; do
    echo "$line"
done < file.txt

# Writing Files
echo "Content" > output.txt
echo "More content" >> output.txt
Enter fullscreen mode Exit fullscreen mode

Arithmetic Operations

# Basic Arithmetic
a=10
b=20
c=$((a + b))
d=$((a * b))

# Arithmetic Expansion
((counter++))
((counter += 5))

# Bc for Complex Math
result=$(echo "scale=2; 10/3" | bc)
Enter fullscreen mode Exit fullscreen mode

Miscellaneous Tips

# Debugging
bash -x script.sh  # Trace script execution
set -x            # Enable debugging
set +x            # Disable debugging

# Comments
# Single-line comment
: '
Multi-line
comment
block
'

# Sleep and Timing
sleep 5        # Wait 5 seconds
time command   # Measure execution time
Enter fullscreen mode Exit fullscreen mode

Best Practices

  1. Always quote variables: "$variable"
  2. Use [[ for advanced string/regex testing
  3. Prefer [[ ]] over [ ] for conditionals
  4. Add error handling and input validation
  5. Use meaningful variable and function names
  6. Comment your code
  7. Keep scripts modular and reusable

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.