Bookmark this page. Use Ctrl+F (or Cmd+F on Mac) to find what you need. This cheat sheet covers essential terminal commands for macOS and Linux.

Last updated: March 2026

CommandDescription
pwdPrint current directory
lsList files
ls -laList all files with details (including hidden)
ls -lhList with human-readable sizes
cd /pathChange directory
cd ~Go to home directory
cd ..Go up one directory
cd -Go to previous directory
treeShow directory tree (install: brew install tree)
tree -L 2Tree with max depth 2

Files and Directories

CommandDescription
touch file.txtCreate empty file
mkdir mydirCreate directory
mkdir -p a/b/cCreate nested directories
cp file.txt copy.txtCopy file
cp -r dir/ newdir/Copy directory recursively
mv file.txt newname.txtRename/move file
rm file.txtDelete file
rm -r dir/Delete directory recursively
rm -rf dir/Force delete (no confirmation)
ln -s target linkCreate symbolic link
cat file.txtPrint file contents
head -20 file.txtFirst 20 lines
tail -20 file.txtLast 20 lines
tail -f file.logFollow file in real-time (logs)
less file.txtPaginated viewer (q to quit)
wc -l file.txtCount lines
wc -w file.txtCount words
diff file1 file2Compare two files
stat file.txtFile details (size, dates, permissions)

Searching

CommandDescription
grep "text" file.txtSearch for text in file
grep -r "text" dir/Search recursively in directory
grep -i "text" file.txtCase-insensitive search
grep -n "text" file.txtShow line numbers
grep -c "text" file.txtCount matches
grep -v "text" file.txtShow lines NOT matching
find . -name "*.txt"Find files by name
find . -type d -name "src"Find directories by name
find . -size +10MFind files larger than 10MB
find . -mtime -7Files modified in last 7 days
which pythonFind where a command lives
locate file.txtFast file search (uses index)

Pipes and Redirection

# Pipe — send output of one command to another
ls -la | grep ".txt"
cat file.txt | sort | uniq
ps aux | grep node

# Redirect output to file
echo "hello" > file.txt          # overwrite
echo "world" >> file.txt         # append

# Redirect errors
command 2> errors.log            # stderr to file
command > output.log 2>&1        # stdout + stderr to file
command &> all.log               # same (bash shorthand)

# /dev/null — discard output
command > /dev/null 2>&1         # silence everything
cmd1 | cmd2      pipe: stdout of cmd1 → stdin of cmd2
cmd > file       redirect stdout to file (overwrite)
cmd >> file      redirect stdout to file (append)
cmd 2> file      redirect stderr to file
cmd < file       use file as stdin

Permissions

-rwxr-xr-- 1 alex staff 4096 Mar 15 file.txt
│├─┤├─┤├─┤
│ │   │  │
│ │   │  └── Others: read only
│ │   └───── Group: read + execute
│ └───────── Owner: read + write + execute
└─────────── File type (- = file, d = directory, l = link)
CommandDescription
chmod 755 filerwxr-xr-x (owner all, group/others read+exec)
chmod 644 filerw-r–r– (owner read+write, others read)
chmod +x script.shAdd execute permission
chmod -w file.txtRemove write permission
chown user:group fileChange owner and group
chown -R user dir/Change owner recursively
NumberPermission
7rwx (read + write + execute)
6rw- (read + write)
5r-x (read + execute)
4r– (read only)
0— (no permission)

Processes

CommandDescription
ps auxList all processes
ps aux | grep nodeFind a specific process
topLive process monitor
htopBetter process monitor (install separately)
kill <pid>Send SIGTERM (graceful stop)
kill -9 <pid>Send SIGKILL (force stop)
killall nodeKill all processes by name
lsof -i :3000Find what is using port 3000
jobsList background jobs
bgResume job in background
fgBring job to foreground
command &Run command in background
nohup command &Run and keep running after logout

Disk and System

CommandDescription
df -hDisk usage (human-readable)
du -sh dir/Directory size
du -sh * | sort -rhLargest items in current dir
free -hMemory usage (Linux)
uname -aSystem info
hostnameMachine name
uptimeSystem uptime and load
dateCurrent date/time
calCalendar

Networking

CommandDescription
curl https://example.comFetch a URL
curl -o file.html https://example.comDownload to file
curl -X POST -d '{"key":"value"}' -H "Content-Type: application/json" urlPOST JSON
wget https://example.com/file.zipDownload a file
ping example.comTest connectivity
ifconfig / ip addrShow network interfaces
netstat -tlnp / ss -tlnpShow listening ports
ssh user@hostConnect via SSH
scp file.txt user@host:/pathCopy file to remote
scp user@host:/path/file.txt .Copy file from remote

Archives

CommandDescription
tar -czf archive.tar.gz dir/Create gzip archive
tar -xzf archive.tar.gzExtract gzip archive
tar -xzf archive.tar.gz -C /destExtract to directory
zip -r archive.zip dir/Create zip archive
unzip archive.zipExtract zip

Text Processing

# Sort lines
sort file.txt
sort -r file.txt              # reverse
sort -n file.txt              # numeric sort
sort -u file.txt              # unique only

# Unique lines (file must be sorted first)
sort file.txt | uniq
sort file.txt | uniq -c       # count occurrences

# Cut columns
cut -d',' -f1,3 data.csv      # columns 1 and 3 (comma delimiter)

# Replace text
sed 's/old/new/g' file.txt    # replace all occurrences
sed -i 's/old/new/g' file.txt # in-place edit (Linux)
sed -i '' 's/old/new/g' file.txt # in-place edit (macOS — needs empty '')

# Print specific lines
awk '{print $1, $3}' file.txt  # columns 1 and 3 (space delimiter)
awk -F',' '{print $1}' data.csv # with custom delimiter

# Count and summarize
cat access.log | awk '{print $1}' | sort | uniq -c | sort -rn | head -10
# → top 10 IP addresses in an access log

Keyboard Shortcuts (Terminal)

ShortcutAction
Ctrl+CCancel current command
Ctrl+DExit shell / close terminal
Ctrl+ZSuspend current process
Ctrl+LClear screen
Ctrl+RSearch command history
Ctrl+AMove cursor to start of line
Ctrl+EMove cursor to end of line
Ctrl+WDelete word before cursor
Ctrl+UDelete entire line before cursor
TabAuto-complete file/command name
!!Repeat last command
!$Last argument of previous command

Environment Variables

echo $HOME                     # print variable
export MY_VAR="value"          # set for current session
echo 'export MY_VAR="value"' >> ~/.zshrc   # permanent (Zsh)
echo 'export MY_VAR="value"' >> ~/.bashrc  # permanent (Bash)
env                            # list all env variables
printenv PATH                  # print specific variable

Common Mistakes

  1. rm -rf / or rm -rf * — There is no recycle bin in the terminal. Deleted files are gone. Always double-check your path before running rm -rf. Use ls first to preview what will be deleted.

  2. Running commands as root unnecessarily — Using sudo for everything is dangerous. Only use sudo when you actually need elevated permissions (installing packages, changing system files).

  3. Not quoting variables in scriptsrm $FILE can delete the wrong thing if $FILE contains spaces. Always use rm "$FILE" with quotes.