by DannyUpdated 10 sections

Works in Bash and, for the most part, zsh. <file> and <dir> are placeholders.

Download the PDF

Move around


_10
pwd # where am I
_10
ls -la # list, including hidden
_10
cd <dir> # go there
_10
cd - # back to the last folder
_10
cd ~ # home

Files and folders


_10
mkdir -p a/b/c # make nested folders
_10
touch notes.txt # new empty file
_10
cp -r src backup # copy a folder
_10
mv old.txt new.txt # move or rename
_10
rm -r <dir> # delete, no undo
_10
ln -s target link # symbolic link

Read files


_10
cat <file> # print it all
_10
less <file> # page through, q to quit
_10
head -n 20 <file> # first 20 lines
_10
tail -f app.log # follow new lines
_10
wc -l <file> # count lines

Find things


_10
find . -name "*.ts" # by name
_10
find . -type f -mtime -1 # changed today
_10
grep -rn "TODO" src # search text
_10
grep -ri "error" app.log # ignore case
_10
which node # where a command is

Pipes and redirects


_10
cmd > out.txt # write, replacing
_10
cmd >> out.txt # append
_10
cmd 2> err.txt # errors only
_10
cmd > all.txt 2>&1 # output and errors
_10
cmd1 | cmd2 # feed output onward
_10
sort data | uniq -c | sort -rn | head

Variables


_10
name="Ann" # no spaces around =
_10
echo "Hi $name" # always quote
_10
today=$(date +%F) # command output
_10
echo "${name:-guest}" # default value
_10
export PORT=3000 # visible to children

Conditions


_10
if [[ -f "$file" ]]; then
_10
echo "exists"
_10
elif [[ -d "$file" ]]; then
_10
echo "is a folder"
_10
else
_10
echo "missing"
_10
fi
_10
[[ -z "$var" ]] && echo "empty"

Loops


_10
for f in *.txt; do
_10
echo "$f"
_10
done
_10
_10
for i in {1..5}; do echo "$i"; done
_10
_10
while read -r line; do
_10
echo "$line"
_10
done < list.txt

Script boilerplate


_10
#!/usr/bin/env bash
_10
set -euo pipefail # stop on errors
_10
_10
main() {
_10
local target="${1:?usage: run.sh <target>}"
_10
echo "Building $target"
_10
}
_10
_10
main "$@"

Make it runnable with chmod +x run.sh.

Processes


_10
cmd & # run in background
_10
jobs # list background jobs
_10
ps aux | grep node # find a process
_10
kill <pid> # ask it to stop
_10
lsof -i :3000 # what is using a port