ShBash · Lesson 8 of 8
Bash Cheatsheet
Daily commands and scripting syntax on one page.
Bash
# ── Navigation & files ──────────────────
pwd; cd dir; cd ..; cd - # - = previous dir
ls -la # all files, details
cp src dst; cp -r dir1 dir2
mv old new # move/rename
rm file; rm -rf dir # careful with -rf
mkdir -p a/b/c
touch file; cat file; less file
head -20 f; tail -f log # -f = follow live
# ── Finding things ──────────────────────
grep -rn "pattern" src/ # recursive + line numbers
grep -i case-insensitive; grep -v invert
find . -name "*.js" -not -path "*/node_modules/*"
which python3; history | grep ssh
# ── Pipes & redirection ─────────────────
cmd > out.txt 2>&1 # both streams to file
cmd >> append.txt
cmd1 | cmd2 # pipe
cmd1 && cmd2 # 2 only if 1 succeeded
cmd1 || echo "failed"
wc -l; sort | uniq -c | sort -rn # count occurrences
cut -d, -f2 file.csv # 2nd CSV column
xargs: find . -name "*.tmp" | xargs rmBash
#!/usr/bin/env bash
set -euo pipefail # strict mode: die on errors
# ── Variables & quoting ─────────────────
name="Ada" # no spaces around =
echo "$name" # ALWAYS quote expansions
result=$(date +%F) # command substitution
n=$(( 2 + 3 )) # arithmetic
# ── Arguments ───────────────────────────
# $0 script $1..$9 args $# count "$@" all args
# $? last exit code $$ this PID
# ── Conditions ──────────────────────────
if [[ -f "$file" ]]; then echo exists; fi
# -f file -d dir -z empty-string -n non-empty
# == != for strings | -eq -ne -lt -gt for numbers
[[ "$a" == "yes" && $n -gt 3 ]]
# ── Loops & functions ───────────────────
for f in *.txt; do echo "$f"; done
for i in {1..5}; do echo "$i"; done
while read -r line; do echo "$line"; done < file
greet() {
local who="$1" # local scope
echo "Hello, $who"
return 0
}
greet "Ada"
case "$1" in
start) run ;;
stop) halt ;;
*) echo "usage: $0 start|stop"; exit 1 ;;
esac