Skip to main content

Linux Commands Reference

A practical reference for everyday Linux commands — navigation, files, text manipulation, permissions, processes, and more. Each entry covers what the command does, when to reach for it, and a real example.

Start here. Before you can do anything useful in the terminal, you need to know where you are and how to move around.

Command What When
pwd Print the current working directory You’re lost and need to confirm where you are
ls List directory contents Checking what’s in the current directory
ls -la List all files including hidden, in long format You need to see permissions, sizes, and hidden files
cd <dir> Change into a directory Moving around the filesystem
pushd <dir> Switch to a directory and save the current one on a stack You need to jump somewhere temporarily and come back exactly
popd Return to the last directory saved by pushd Returning after a pushd detour
pwd
# /Users/kyaw/projects/myapp

ls
# README.md  src/  tests/  package.json

ls -la
# drwxr-xr-x  5 kyaw staff  160 Jun 18 10:00 src
# -rw-r--r--  1 kyaw staff 1234 Jun 18 09:55 README.md

cd src/
cd ..          # go up one level
cd -           # return to previous directory
cd ~           # go to home directory

pushd /tmp
# /tmp ~/projects/myapp   ← stack shown
popd
# ~/projects/myapp        ← back where you were

Files & Directories

Once you know where you are, you need to create, copy, move, and delete things. These are the building blocks for all file management.

Command What When
touch <file> Create an empty file or update its timestamp Creating a placeholder file or resetting a timestamp
mkdir <dir> Create a new directory Setting up a new project or folder structure
cp <src> <dst> Copy a file or directory Duplicating files before editing, or backing up
mv <src> <dst> Move or rename a file/directory Renaming files or reorganising directory structure
rm <file> Delete a file Removing temporary files or old artifacts
ln -s <target> <link> Create a symbolic link Pointing a stable path to a versioned or nested target
find <dir> <expr> Search for files matching a pattern Locating files by name, type, age, or size across a tree
touch notes.txt
touch src/main.swift

mkdir configs
mkdir -p deploy/prod/secrets   # creates all intermediate dirs

cp notes.txt notes_backup.txt
cp -r src/ src_backup/
cp -i important.txt /tmp/      # prompt before overwrite

mv old_name.txt new_name.txt   # rename
mv file.txt ~/Documents/       # move

rm temp.log
rm -r build/                   # delete directory tree
rm -rf node_modules/           # force-delete without prompts

ln -s /usr/local/bin/python3 ~/bin/python

# Find all .swift files modified in the last 7 days
find . -name "*.swift" -mtime -7

# Find all directories named "build"
find . -type d -name "build"

# Find and delete all .DS_Store files
find . -name ".DS_Store" -exec rm {} \;

Viewing Files

Before you can process or search files, you need to read them. These commands get content out of files and onto your screen.

Command What When
cat <file> Print a file’s entire contents to stdout Short files or feeding content into a pipeline
less <file> Page through a file interactively Reading long logs or files you don’t want to flood the terminal with
head <file> Show the first 10 lines Checking the format or header of a file quickly
tail <file> Show the last 10 lines Reviewing the most recent log entries
tail -f <file> Follow a file as it grows in real time Monitoring a live log during a deploy or debug session
wc <file> Count lines, words, and bytes Getting a quick sense of file size or line count
file <path> Identify a file’s type without relying on the extension Inspecting an unknown or binary file before opening it
cat package.json
cat file1.txt file2.txt        # concatenate two files

less server.log                # arrow keys to scroll, /error to search, q to quit

head -n 20 README.md           # first 20 lines
tail -n 50 app.log             # last 50 lines
tail -f /var/log/syslog        # follow live — Ctrl-C to stop

wc -l src/*.swift              # count lines in all Swift files
wc -w essay.md                 # word count

file mystery_binary
# mystery_binary: ELF 64-bit LSB executable, x86-64

Redirection & Pipes

This is the glue that connects everything else. Once you know how to view files, you need to know how to chain commands together and control where their output goes — because most real-world terminal work is a pipeline.

Command What When
cmd > file Redirect stdout to a file, overwriting it Saving command output to a file for later review
cmd >> file Redirect stdout, appending to a file Accumulating logs without wiping previous entries
cmd 2> file Redirect stderr to a file Capturing error output separately from normal output
cmd > file 2>&1 Redirect both stdout and stderr to the same file Capturing all output from a build or test run
cmd1 | cmd2 Pipe stdout of one command into stdin of the next Chaining tools into a processing pipeline
tee <file> Write stdin to both a file and stdout simultaneously Saving output to a file while still watching it in the terminal
ls -la > listing.txt
echo "started" >> deploy.log

make build 2> errors.log
./run_tests.sh > all_output.log 2>&1

# Sort IPs and count occurrences
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -20

# Save test output while watching it live
./run_tests.sh | tee test_results.log

# Find large files, sort by size, show top 10
du -sh /var/log/* 2>/dev/null | sort -rh | head -10

Text Manipulation

With pipes in place, you can feed file content through text-processing tools to extract, transform, and filter exactly what you need.

Command What When
grep <pattern> <file> Search for lines matching a pattern Finding errors in logs, locating a symbol across files
sed 's/old/new/g' Stream editor — find and replace text Batch-replacing strings across a file without opening an editor
awk '{print $N}' Pattern scanning and field extraction Extracting a specific column from structured output
sort <file> Sort lines alphabetically or numerically Ordering output before deduplication or diffing
uniq <file> Remove or count adjacent duplicate lines Deduplicating a sorted list or counting frequency
cut -d: -f1 Extract specific fields from delimited text Pulling columns out of CSV, /etc/passwd, or log output
tr <set1> <set2> Translate or delete characters Case conversion, stripping unwanted characters
xargs <cmd> Build and execute commands from stdin Turning piped filenames or lines into arguments for another command
grep "error" app.log
grep -rn "TODO" src/                        # recursive, show line numbers
grep -i "warning" build.log                 # case-insensitive
grep -v "DEBUG" app.log                     # invert — exclude matching lines

sed 's/localhost/api.prod.com/g' config.json
sed -i 's/localhost/api.prod.com/g' config.json   # edit in place

awk '{print $2}' access.log                 # second column
awk '{sum += $3} END {print sum}' sales.csv # sum third column
awk '$1 == "ERROR" {print $0}' app.log      # filter by first field

sort names.txt
sort -rn scores.txt                         # numeric, reversed
sort -u emails.txt                          # sort and deduplicate

# Count how many times each IP appears in a log
sort access.log | uniq -c | sort -rn | head -10

cut -d: -f1 /etc/passwd                     # extract usernames
cut -d, -f2,4 data.csv                      # columns 2 and 4 from CSV

echo "hello world" | tr 'a-z' 'A-Z'        # uppercase
echo "abc123def456" | tr -d '0-9'           # delete digits

find . -name "*.log" | xargs rm             # delete all found log files
cat urls.txt | xargs -n1 curl -O            # download each URL

Permissions

Now that you can read and manipulate files, you need to control who else can. Permissions determine what each user and group can do with a file.

Command What When
chmod <mode> <file> Change file permissions Making a script executable or locking down sensitive files
chown <user>:<group> <file> Change file owner and group Fixing ownership after copying files as root or between users
chgrp <group> <file> Change only the group ownership Giving a service group access without changing the owner
umask <mask> Set the default permission mask for new files Hardening a server so new files aren’t world-readable by default
chmod +x deploy.sh                          # make executable
chmod 755 /usr/local/bin/mytool             # rwxr-xr-x
chmod go-w sensitive.conf                   # remove write for group and others
chmod 700 ~/.ssh/id_rsa                     # owner-only access

chown deploy:www /var/www/html
chown -R kyaw:staff ~/projects/             # recursive

chgrp docker /var/run/docker.sock

umask                                       # check current mask (e.g. 0022)
umask 077                                   # private: new files are 600

Processes

Files are static. At some point you need to manage what’s running — starting, monitoring, and stopping processes on your machine.

Command What When
ps aux List all running processes with CPU and memory Finding the PID of a process you need to kill or inspect
top Live process monitor Diagnosing high CPU or memory usage in real time
kill <PID> Send a signal to a process Stopping a hung or misbehaving process by its PID
killall <name> Kill all processes matching a name Quickly stopping all instances of a program by name
bg Resume a stopped job in the background Continuing a paused task without blocking the terminal
fg Bring a background job to the foreground Re-attaching to a backgrounded job to see its output
jobs List active background and suspended jobs Checking what’s running in the current shell session
nohup <cmd> & Run a command that survives terminal close Keeping a long-running job alive after you log out
ps aux
ps aux | grep nginx                        # find the nginx process

# Press M to sort by memory, P for CPU, q to quit
top

kill 12345
kill -9 12345                              # force kill (SIGKILL)

killall node                               # kill all node processes

python train.py
# Ctrl-Z  → suspended
bg                                         # resume in background
jobs
# [1]+  Running    python train.py &
fg %1                                      # bring job 1 back

nohup python -m http.server 8080 &

Networking

Processes communicate over the network. These commands let you test connectivity, transfer data, and inspect what’s listening on which ports.

Command What When
ping <host> Check if a host is reachable Diagnosing connectivity issues or measuring round-trip latency
curl <url> Transfer data to/from a URL Testing APIs, downloading files, or inspecting HTTP responses
wget <url> Download a file from a URL Fetching files in scripts where curl isn’t available
ssh <user>@<host> Open a secure shell session on a remote machine Accessing servers, running remote commands, or setting up tunnels
scp <src> <dst> Securely copy files between machines Transferring files to/from a server without mounting a share
ss -tuln Show listening TCP/UDP sockets Checking which ports are open and which process is using them
ping -c 4 google.com

curl https://api.example.com/users
curl -X POST https://api.example.com/login \
     -H "Content-Type: application/json" \
     -d '{"email":"you@example.com","password":"secret"}'
curl -o release.tar.gz https://example.com/release.tar.gz
curl -I https://example.com                # headers only

wget https://example.com/archive.zip
wget -O myfile.zip https://example.com/archive.zip

ssh kyaw@192.168.1.10
ssh -i ~/.ssh/deploy_key deploy@prod.example.com
ssh -L 8080:localhost:80 kyaw@remote-server.com   # port forward

scp ./build.tar.gz kyaw@prod:/var/deploys/
scp kyaw@prod:/var/log/app.log ./local_copy.log
scp -r ./dist/ kyaw@prod:/var/www/html/

ss -tuln                                   # all listening sockets
ss -tuln | grep :3000                      # is port 3000 open?

Archives & Compression

When you transfer files over the network or store backups, you need to bundle and compress them first.

Command What When
tar -czf <out> <src> Create a gzip-compressed tar archive Packaging a directory tree for transfer or backup
tar -xzf <file> Extract a gzip-compressed tar archive Unpacking a release tarball or backup
tar -tf <file> List the contents of a tar archive Previewing what’s inside before extracting
gzip <file> Compress a single file with gzip Reducing log file size or compressing before uploading
gunzip <file.gz> Decompress a gzip file Restoring a compressed log or config file
zip -r <out> <src> Create a zip archive Sharing with systems or tools that don’t understand tar
unzip <file> Extract a zip archive Unpacking files received from non-Linux systems
tar -czf src_backup.tar.gz src/
tar -xzf src_backup.tar.gz
tar -xzf release.tar.gz -C /opt/myapp/    # extract to specific dir
tar -tf archive.tar.gz                     # list contents

gzip large_log.log                         # produces large_log.log.gz
gzip -k large_log.log                      # keep original
gunzip large_log.log.gz

zip -r frontend.zip dist/
unzip frontend.zip
unzip frontend.zip -d /var/www/html/

System Info

Finally, when something goes wrong — or you just want a health check — these commands give you a snapshot of the machine itself.

Command What When
uname -a Print all system information Checking kernel version or architecture before installing software
df -h Show disk space usage in human-readable form Diagnosing a full disk or planning a deployment
du -sh <dir> Show total size of a directory Finding what’s eating your disk space
free -h Show RAM and swap usage Diagnosing out-of-memory conditions or sizing a server
uptime Show how long the system has been running and load averages Quick health check — high load averages signal CPU pressure
whoami Print the current user’s name Confirming which user you’re acting as, especially after su
which <cmd> Show the full path to an executable Verifying which version of a tool the shell is resolving
history List previously run commands Recovering a forgotten command or auditing recent activity
uname -a
# Linux hostname 5.15.0 #1 SMP x86_64 GNU/Linux

df -h
# Filesystem  Size  Used  Avail  Use%  Mounted on
# /dev/sda1    50G   18G    30G   38%  /

du -sh ~/projects/
du -sh /var/log/*                          # compare sizes

free -h
#               total   used    free    available
# Mem:           16Gi   8.2Gi   4.1Gi      7.2Gi

uptime
# 10:30:01 up 3 days, 2:15, load average: 0.42, 0.38, 0.35

whoami
# kyaw

which python3
# /usr/local/bin/python3

history | grep "docker build"
# 423  docker build -t myapp:latest .