ENGIMY.IO - CHEATSHEET
BASH × QUICK REFERENCE
REFERENCE vBash 5.x

Bash Quick Reference

Everything you need day‑to‑day – commands, scripting, and system administration.

Basic Commands

File Operations
  • lslist directory
  • ls -lalist with details and hidden
  • cdchange directory
  • pwdprint working directory
  • mkdir dircreate directory
  • touch filecreate empty file / update timestamp
  • cp src destcopy file/directory
  • mv src destmove or rename
  • rm fileremove file
  • rm -rf dirremove directory forcefully
  • ln -s target linksymbolic link
File Viewing
  • cat filedisplay entire file
  • less fileview file interactively
  • head filefirst 10 lines
  • tail filelast 10 lines
  • tail -f filefollow file (live)
  • wc fileword/line/char count
  • find / -name "file"search for files
  • grep pattern filesearch for pattern
  • diff file1 file2compare files

Permissions

chmod 755 file    # rwxr-xr-x
chmod +x script   # make executable
chown user:group file # change owner/group

Redirections

# Output redirection
command > file    # stdout to file (overwrite)
command >> file   # stdout to file (append)
command 2> file   # stderr to file
command &> file   # stdout + stderr to file

# Input redirection
command < file    # read from file
command << EOF    # heredoc
...
EOF

# Pipes (stdout of one to stdin of another)
command1 | command2

# Examples
ls -la | grep ".txt"
cat file | sort | uniq -c

Variables

# Define variable (no spaces around =)
name="Alice"
age=25

# Use variable
echo $name
echo "$name is $age years old"

# Command substitution
current_dir=$(pwd)
files=$(ls)

# Environment variables
export PATH=$PATH:/custom/bin
export EDITOR=vim

# Read from user
read -p "Enter your name: " username
echo "Hello, $username"

# Special variables
# $0  – script name
# $1..$9 – positional arguments
# $#  – number of arguments
# $*  – all arguments as a single string
# $@  – all arguments as separate words
# $?  – exit status of last command
# $$  – process ID of current script

Conditionals

if / elif / else

if [ condition ]; then
    # commands
elif [ condition ]; then
    # commands
else
    # commands
fi

File Tests

# Common file tests
[ -f "file" ]   # file exists and is regular
[ -d "dir" ]    # directory exists
[ -e "path" ]   # path exists
[ -r "file" ]   # readable
[ -w "file" ]   # writable
[ -x "file" ]   # executable
[ -s "file" ]   # non‑empty

# Example
if [ -f "$1" ]; then
    echo "File exists"
fi

String Tests

[ -z "$str" ]     # string is empty
[ -n "$str" ]     # string is non‑empty
[ "$a" = "$b" ]     # strings equal
[ "$a" != "$b" ]    # strings not equal
[[ "$a" > "$b" ]]   # string comparison (lexicographic)

# Example
if [ -z "$name" ]; then
    echo "Name is empty"
fi

Numeric Tests

[ "$a" -eq "$b" ]  # equal
[ "$a" -ne "$b" ]  # not equal
[ "$a" -lt "$b" ]  # less than
[ "$a" -le "$b" ]  # less or equal
[ "$a" -gt "$b" ]  # greater than
[ "$a" -ge "$b" ]  # greater or equal

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

Logical Operators

# AND
[ condition1 ] && [ condition2 ]
[ condition1 -a condition2 ]   # (legacy)

# OR
[ condition1 ] || [ condition2 ]
[ condition1 -o condition2 ]   # (legacy)

# NOT
[ ! condition ]

# Example
if [ -f "$file" ] && [ -r "$file" ]; then
    cat "$file"
fi

Case Statement

case "$var" in
    "start")
        echo "Starting..."
        ;;
    "stop")
        echo "Stopping..."
        ;;
    "restart")
        echo "Restarting..."
        ;;
    *)
        echo "Unknown command"
        ;;
esac

Loops

for Loop

# Iterate over list
for item in apple banana orange; do
    echo $item
done

# Iterate over range
for i in {1..5}; do
    echo $i
done

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

# Iterate over files
for file in *.txt; do
    echo "Processing $file"
done

while Loop

# Basic while
i=1
while [ $i -le 5 ]; do
    echo $i
    ((i++))
done

# Read lines from file
while IFS= read -r line; do
    echo "$line"
done < file.txt

# Infinite loop
while true; do
    echo "Running..."
    sleep 1
done

until Loop

# Runs until condition is true
i=1
until [ $i -gt 5 ]; do
    echo $i
    ((i++))
done

Functions

# Define function
function greet() {
    local name="$1"   # local variable
    echo "Hello, $name!"
    return 0
}

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

# Function with return value (exit status)
is_even() {
    if [ $(("$1" % 2)) -eq 0 ]; then
        return 0
    else
        return 1
    fi
}

# Call function
greet "Alice"
if is_even 4; then
    echo "Even"
fi

# Function with output capture
result=$(greet "Bob")

Arrays

# Define array
fruits=(apple banana orange)
fruits[3]=grape

# Access elements
echo ${fruits[0]}      # apple
echo ${fruits[@]}      # all elements
echo ${#fruits[@]}     # length

# Iterate over array
for fruit in "${fruits[@]}"; do
    echo $fruit
done

# Slice array
echo ${fruits[@]:1:2}  # banana orange

String Manipulation

# Length
str="Hello"
echo ${#str}          # 5

# Substring
echo ${str:1:3}       # ell

# Replace first occurrence
echo ${str/"l"/"x"}   # Hexlo

# Replace all occurrences
echo ${str//"l"/"x"}  # Hexxo

# Remove prefix
path="/home/user/file.txt"
echo ${path#/home/}   # user/file.txt
echo ${path##*/}      # file.txt (basename)

# Remove suffix
echo ${path%.txt}     # /home/user/file
echo ${path%/*}       # /home/user (dirname)

# Convert to uppercase/lowercase
str="hello"
echo ${str^^}         # HELLO
echo ${str,,}         # hello

Script Header (Shebang)

#!/bin/bash
# Script description

set -e              # exit on error
set -u              # exit on undefined variable
set -x              # debug mode (print commands)
set -o pipefail     # fail on pipe errors

Common Commands Reference

Process Management
  • ps auxlist processes
  • top / htopprocess monitor
  • kill PIDsend signal
  • kill -9 PIDforce kill
  • bgbackground job
  • fgforeground job
  • jobslist background jobs
  • nohup command &run in background
System Info
  • uname -asystem info
  • df -hdisk usage
  • du -sh dirdirectory size
  • free -hmemory usage
  • whoamicurrent user
  • whologged in users
  • datecurrent date/time
  • uptimesystem uptime

Text Processing Tools

grep

grep pattern file         # search
grep -i pattern file      # case‑insensitive
grep -v pattern file      # invert match
grep -r pattern dir/      # recursive
grep -c pattern file      # count matches
grep -E "regex" file     # extended regex

sed

sed 's/old/new/g' file   # replace all
sed -n '5p' file         # print line 5
sed '/pattern/d' file     # delete matching lines
sed -i 's/old/new/g' file # in‑place edit

awk

awk '{print $1}' file    # print first column
awk '$2 > 10' file        # filter by column
awk -F ',' '{print $1}' file # custom delimiter
awk 'BEGIN{FS=","} {print $2}' file

Best Practices

  • Add shebang#!/bin/bash or #!/usr/bin/env bash.
  • Use set -e to exit on error and set -u for undefined variables.
  • Use [[ ]] instead of [ ] for more features and safety.
  • Quote variables"$var" to prevent word splitting.
  • Use local for variables inside functions.
  • Use $(command) instead of backticks for command substitution.
  • Use printf instead of echo for formatting.
  • Use read -r to prevent backslash interpretation.
  • Add usage messagesecho "Usage: $0 arg1 arg2".
  • Use trap for cleanup on script exit.
  • Check exit statusif ! command; then.
  • Use shellcheck to validate your scripts.
📌 Quick Reference
Check Bash version: bash --version
Make script executable: chmod +x script.sh
Run script: ./script.sh or bash script.sh
Debug script: bash -x script.sh
Validate script: shellcheck script.sh
← Back to All Cheatsheets