Originally published byDev.to
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")
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
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
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
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
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
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
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
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
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
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
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)
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
Best Practices
- Always quote variables:
"$variable" - Use
[[for advanced string/regex testing - Prefer
[[ ]]over[ ]for conditionals - Add error handling and input validation
- Use meaningful variable and function names
- Comment your code
- Keep scripts modular and reusable
🇺🇸
More news from United StatesUnited States
NORTH AMERICA
Related News
How Braze’s CTO is rethinking engineering for the agentic area
11h ago
Amazon Employees Are 'Tokenmaxxing' Due To Pressure To Use AI Tools
22h ago
KDE Receives $1.4 Million Investment From Sovereign Tech Fund
2h ago
Instagram’s new ‘Instants’ feature combines elements from Snapchat and BeReal
2h ago
Six Claude Code Skills That Close the AI Agent Feedback Loop
2h ago