Skip to content

Terminal & Scripting — cheat sheet

A one-page lookup for the commands used across this course. Grouped by task; the course pages cover the why behind each one — this page is just the what.

Task Command
Print the current directory pwd
Change directory cd <path> (cd - returns to the previous directory)
List files (long format) ls -l
List including hidden (dotfiles) ls -a
Change permissions (symbolic) chmod u+x file
Change permissions (octal) chmod 755 file
Change owner (and group) chown user:group file
Change group only chgrp group file
Apply recursively chmod -R <mode> <dir> (check what's inside first)

Pipes & redirection

Task Command
Chain one command's output into the next cmd1 \| cmd2
Redirect stdout to a file (overwrite) cmd > file
Redirect stdout to a file (append) cmd >> file
Feed a file in as stdin cmd < file
Redirect stderr only cmd 2> file
Redirect both stdout and stderr cmd &> file (or cmd > file 2>&1)

Text processing

Task Command
Find matching lines grep <pattern> file
Case-insensitive / recursive / invert / count grep -i / -r / -v / -c
Replace text on each line (preview) sed 's/old/new/' file
Replace in place sed -i 's/old/new/' file
Replace every match on a line, not just the first sed 's/old/new/g' file
Print a column (whitespace-separated) awk '{print $1}' file
Print a column with a custom delimiter awk -F, '{print $2}' file
Extract a delimited field without full awk cut -d',' -f2 file
Sort lines (alphabetic / numeric / reverse) sort / sort -n / sort -r
Count adjacent duplicate lines sort file \| uniq -c

Process monitoring

Task Command
Snapshot of every process ps aux
Live, continuously refreshing view top (or htop)
Run a command in the background command &
List this shell's background jobs jobs
Bring a job to the foreground fg %<job-number>
Resume a job in the background bg %<job-number>
Keep a job running after logout nohup command &
Politely ask a process to stop kill <PID> (sends SIGTERM)
Force-terminate immediately kill -9 <PID> (sends SIGKILL)
Show the last command's exit code echo $?

Bash scripting

Task Syntax
Shebang line (first line of every script) #!/usr/bin/env bash
Make a script executable chmod +x script.sh
Fail fast on error / unset var / pipeline failure set -euo pipefail
Read an argument / all arguments / arg count $1 / $@ / $#
Conditional if [[ -f "$file" ]]; then ... fi
For loop for f in *.log; do ... done
While loop reading a file line by line while read -r line; do ... done < file
Define a function name() { local x="$1"; ...; return 0; }
Exit the script with a status code exit <n>

How this connects

The navigation/permissions page covers reading and setting the modes chmod above accepts, the text processing page covers when to reach for grep/sed/awk versus cut/sort/uniq, the process page covers what each signal actually does to a running process, and the scripting page covers wiring all of the above into a script that fails loudly instead of silently.