Skip to content
AgileLogics

Bash Cheat Sheet

Learn Bash from the basics →

Navigation & Files

pwd / cd dir / cd .. / cd ~
Where am I / change directory
ls -la
List all files, with details
mkdir -p a/b/c
Create nested directories
cp -r src dst / mv old new
Copy / move or rename
rm file / rm -r dir
Delete (no undo!)
cat / less / head -n 5 / tail -f
View files

Variables & Quoting

name="Ada"
Assign (no spaces around =)
echo "Hello, $name"
Double quotes expand variables
echo 'Literal $name'
Single quotes are literal
today=$(date +%F)
Command substitution
echo $(( 7 * 6 ))
Integer arithmetic
${name:-default}
Default if unset or empty

Pipes & Redirection

cmd > out.txt / cmd >> out.txt
Write / append stdout to a file
cmd 2> errors.txt / cmd &> all.txt
Redirect stderr / both
cmd < input.txt
Read stdin from a file
cmd1 | cmd2
Pipe output into another command
cmd1 && cmd2 / cmd1 || cmd2
Run next on success / on failure

Conditionals & Loops

if [[ -f file ]]; then ... elif ...; else ...; fi
If statement
[[ $a == "$b" ]] / (( n > 5 ))
String / numeric tests
-f file / -d dir / -z "$s" / -n "$s"
File and string tests
for f in *.txt; do ...; done
Loop over files
while IFS= read -r line; do ...; done < file
Read a file line by line
case "$x" in start) ...;; *) ...;; esac
Pattern matching

Functions & Arrays

greet() { local name=$1; echo "Hi $name"; }
Function with a local variable
"$@" / $# / $0 / $?
All args / count / script name / last exit code
arr=(a b c); echo "${arr[1]}" "${#arr[@]}"
Indexed array, element, length
declare -A ages=([ada]=36); echo "${ages[ada]}"
Associative array

Text Processing

grep -rn "TODO" src/
Search recursively, with line numbers
sed 's/old/new/g' file
Find and replace
awk -F, '{ print $2 }' data.csv
Print the second column
sort | uniq -c | sort -rn
Count and rank lines
cut -d, -f1,3 / wc -l / tr a-z A-Z
Columns / count lines / translate
find . -name '*.log' -mtime +7 -delete
Find and act on files

Robust Scripts

#!/usr/bin/env bash
Shebang line
set -euo pipefail
Stop on errors, unset variables, and pipe failures
trap cleanup EXIT
Always run cleanup
tmp=$(mktemp -d)
Safe temporary directory
shellcheck script.sh
Lint for common bugs