Shell (Bash)
Updated: September 8, 2025Categories: DevOps, Linux, Command Line
Printed from:
Bash Cheatsheet
Language Overview
Bash (Bourne Again SHell) is a powerful Unix shell and command language used for:
- Automating system tasks
- Writing shell scripts
- Interacting with operating systems
- System administration and DevOps
Basic Syntax
Script Structure
Bash
123456#!/bin/bash # Shebang line
# This is a comment
# Basic script example
echo "Hello, World!"
Command Execution
Bash
123456# Running commands
command [options] [arguments]
# Example
ls -la /home/user
Data Types
Primitive Types
- Strings: Text data (default type)
- Integers: Whole numbers
- Booleans: Represented by exit codes (0 = true, non-zero = false)
Type Examples
Bash
12345678910111213# Strings
name="John Doe"
greeting='Hello, world!'
# Integers
age=30
count=$((10 + 5))
# Boolean equivalents
if [ $? -eq 0 ]; then
echo "Previous command succeeded"
fi
Variables and Constants
Variable Declaration
Bash
123456789101112# Local variables
local_var="local value"
# Global variables
GLOBAL_VAR="global value"
# Read-only (constant)
readonly CONSTANT_VAR="cannot be changed"
# Environment variables
export PATH=$PATH:/new/path
Parameter Expansion
Bash
12345678910111213# Default values
name=${USER:-"Anonymous"}
# Substring extraction
string="Hello, World!"
echo ${string:0:5} # Outputs: Hello
# Length of string
echo $ # Outputs: 13
# Replace substring
echo ${string/World/Bash}
Operators
Arithmetic Operators
Bash
123456789# Basic arithmetic
a=10
b=20
echo $((a + b)) # Addition
echo $((a - b)) # Subtraction
echo $((a * b)) # Multiplication
echo $((b / a)) # Division
echo $((b % a)) # Modulus
Comparison Operators
Bash
1234567891011121314# Numeric comparisons
[ 10 -eq 10 ] # Equal
[ 10 -ne 20 ] # Not equal
[ 10 -lt 20 ] # Less than
[ 10 -le 20 ] # Less than or equal
[ 20 -gt 10 ] # Greater than
[ 20 -ge 10 ] # Greater than or equal
# String comparisons
[ "$str1" = "$str2" ] # Equal
[ "$str1" != "$str2" ] # Not equal
[ -z "$str" ] # Zero length
[ -n "$str" ] # Non-zero length
Control Structures
Conditional Statements
Bash
123456789101112# If-Else
if [ condition ]; then
# commands
elif [ another_condition ]; then
# commands
else
# commands
fi
# Compact if
[ condition ] && command1 || command2
Loops
Bash
1234567891011121314151617181920# For loop
for item in {1..5}; do
echo $item
done
# C-style for loop
for ((i=0; i<5; i++)); do
echo $i
done
# While loop
while [ condition ]; do
# commands
done
# Until loop
until [ condition ]; do
# commands
done
Loop Control
Bash
1234567891011# Break and continue
for i in {1..10}; do
if [ $i -eq 5 ]; then
break # Exit loop
fi
if [ $i -eq 3 ]; then
continue # Skip iteration
fi
echo $i
done
Functions
Function Definition
Bash
12345678910111213141516171819# Basic function
greet() {
echo "Hello, $1!"
}
greet "World"
# Function with return value
add() {
return $((${1} + ${2}))
}
add 5 3
echo $? # Prints result
# Function with local variables
calculate() {
local result=$((${1} * ${2}))
echo $result
}
Arrays
Indexed Arrays
Bash
123456789101112# Declaration
fruits=("apple" "banana" "cherry")
# Access elements
echo ${fruits[0]} # First element
echo ${fruits[@]} # All elements
echo $ # Array length
# Modifying arrays
fruits+=("date") # Append
unset fruits[1] # Remove element
Associative Arrays
Bash
12345678910# Declare associative array
declare -A person=(
[name]="John"
[age]=30
[city]="New York"
)
# Access
echo ${person[name]}
Input/Output
Redirection
Bash
12345678910# Output redirection
echo "Hello" > file.txt # Overwrite
echo "World" >> file.txt # Append
# Input redirection
sort < input.txt > sorted.txt
# Error redirection
command 2> error.log
Piping
Bash
123# Pipe output between commands
cat file.txt | grep "pattern" | sort
Text Processing
Basic Tools
Bash
123456789# Grep (search)
grep "pattern" file.txt
# Sed (stream editor)
sed 's/old/new/g' file.txt
# Awk (text processing)
awk '{print $1}' file.txt
Process Management
Bash
12345678910# Background jobs
command & # Run in background
jobs # List background jobs
fg %1 # Bring job to foreground
# Process control
ps aux # List processes
kill PID # Terminate process
killall process_name # Kill all processes with name
Environment and Configuration
Bash
1234567# Environment variables
printenv # Show all variables
export VARNAME=value # Set environment variable
# Shell configuration
source ~/.bashrc # Reload configuration
Error Handling
Bash
12345678910# Exit codes
command
echo $? # Check exit status (0 = success)
# Error checking
if ! command; then
echo "Command failed"
exit 1
fi
File Operations
Bash
1234567891011# File tests
[ -f file.txt ] # Regular file exists
[ -d directory ] # Directory exists
[ -r file ] # File is readable
[ -w file ] # File is writable
[ -x file ] # File is executable
# Permissions
chmod 755 script.sh # Change file permissions
chown user:group file # Change ownership
Best Practices
- Use
set -euo pipefailfor robust error handling - Quote variables to prevent word splitting
- Use
shellcheckfor static analysis - Write modular, well-commented scripts
- Use meaningful variable and function names
Testing Shell Scripts
- Use
bats(Bash Automated Testing System) - Write test cases covering various scenarios
- Mock external commands
- Test edge cases and error conditions
Security Considerations
- Validate and sanitize input
- Use
--to prevent option injection - Avoid using
eval - Limit use of
sudo - Use
read -sfor sensitive inputs
Resources for Further Learning
- Bash Hackers Wiki
- Advanced Bash-Scripting Guide
- ShellCheck (linting tool)
- LinuxConfig.org Bash tutorials
- Official Bash documentation
Conclusion
Bash is a powerful scripting language for system administration, automation, and command-line interaction. Master its syntax, understand its nuances, and practice regularly to become proficient.
Continue Learning
Discover more cheatsheets to boost your productivity