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.

CommandWhatWhen
pwdPrint the current working directoryYou’re lost and need to confirm where you are
lsList directory contentsChecking what’s in the current directory
ls -laList all files including hidden, in long formatYou need to see permissions, sizes, and hidden files
cd <dir>Change into a directoryMoving around the filesystem
pushd <dir>Switch to a directory and save the current one on a stackYou need to jump somewhere temporarily and come back exactly
popdReturn to the last directory saved by pushdReturning 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.

CommandWhatWhen
touch <file>Create an empty file or update its timestampCreating a placeholder file or resetting a timestamp
mkdir <dir>Create a new directorySetting up a new project or folder structure
cp <src> <dst>Copy a file or directoryDuplicating files before editing, or backing up
mv <src> <dst>Move or rename a file/directoryRenaming files or reorganising directory structure
rm <file>Delete a fileRemoving temporary files or old artifacts
ln -s <target> <link>Create a symbolic linkPointing a stable path to a versioned or nested target
find <dir> <expr>Search for files matching a patternLocating 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.

CommandWhatWhen
cat <file>Print a file’s entire contents to stdoutShort files or feeding content into a pipeline
less <file>Page through a file interactivelyReading long logs or files you don’t want to flood the terminal with
head <file>Show the first 10 linesChecking the format or header of a file quickly
tail <file>Show the last 10 linesReviewing the most recent log entries
tail -f <file>Follow a file as it grows in real timeMonitoring a live log during a deploy or debug session
wc <file>Count lines, words, and bytesGetting a quick sense of file size or line count
file <path>Identify a file’s type without relying on the extensionInspecting 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.

CommandWhatWhen
cmd > fileRedirect stdout to a file, overwriting itSaving command output to a file for later review
cmd >> fileRedirect stdout, appending to a fileAccumulating logs without wiping previous entries
cmd 2> fileRedirect stderr to a fileCapturing error output separately from normal output
cmd > file 2>&1Redirect both stdout and stderr to the same fileCapturing all output from a build or test run
cmd1 | cmd2Pipe stdout of one command into stdin of the nextChaining tools into a processing pipeline
tee <file>Write stdin to both a file and stdout simultaneouslySaving 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.

CommandWhatWhen
grep <pattern> <file>Search for lines matching a patternFinding errors in logs, locating a symbol across files
sed 's/old/new/g'Stream editor — find and replace textBatch-replacing strings across a file without opening an editor
awk '{print $N}'Pattern scanning and field extractionExtracting a specific column from structured output
sort <file>Sort lines alphabetically or numericallyOrdering output before deduplication or diffing
uniq <file>Remove or count adjacent duplicate linesDeduplicating a sorted list or counting frequency
cut -d: -f1Extract specific fields from delimited textPulling columns out of CSV, /etc/passwd, or log output
tr <set1> <set2>Translate or delete charactersCase conversion, stripping unwanted characters
xargs <cmd>Build and execute commands from stdinTurning 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.

CommandWhatWhen
chmod <mode> <file>Change file permissionsMaking a script executable or locking down sensitive files
chown <user>:<group> <file>Change file owner and groupFixing ownership after copying files as root or between users
chgrp <group> <file>Change only the group ownershipGiving a service group access without changing the owner
umask <mask>Set the default permission mask for new filesHardening 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.

CommandWhatWhen
ps auxList all running processes with CPU and memoryFinding the PID of a process you need to kill or inspect
topLive process monitorDiagnosing high CPU or memory usage in real time
kill <PID>Send a signal to a processStopping a hung or misbehaving process by its PID
killall <name>Kill all processes matching a nameQuickly stopping all instances of a program by name
bgResume a stopped job in the backgroundContinuing a paused task without blocking the terminal
fgBring a background job to the foregroundRe-attaching to a backgrounded job to see its output
jobsList active background and suspended jobsChecking what’s running in the current shell session
nohup <cmd> &Run a command that survives terminal closeKeeping 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.

CommandWhatWhen
ping <host>Check if a host is reachableDiagnosing connectivity issues or measuring round-trip latency
curl <url>Transfer data to/from a URLTesting APIs, downloading files, or inspecting HTTP responses
wget <url>Download a file from a URLFetching files in scripts where curl isn’t available
ssh <user>@<host>Open a secure shell session on a remote machineAccessing servers, running remote commands, or setting up tunnels
scp <src> <dst>Securely copy files between machinesTransferring files to/from a server without mounting a share
ss -tulnShow listening TCP/UDP socketsChecking 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.

CommandWhatWhen
tar -czf <out> <src>Create a gzip-compressed tar archivePackaging a directory tree for transfer or backup
tar -xzf <file>Extract a gzip-compressed tar archiveUnpacking a release tarball or backup
tar -tf <file>List the contents of a tar archivePreviewing what’s inside before extracting
gzip <file>Compress a single file with gzipReducing log file size or compressing before uploading
gunzip <file.gz>Decompress a gzip fileRestoring a compressed log or config file
zip -r <out> <src>Create a zip archiveSharing with systems or tools that don’t understand tar
unzip <file>Extract a zip archiveUnpacking 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.

CommandWhatWhen
uname -aPrint all system informationChecking kernel version or architecture before installing software
df -hShow disk space usage in human-readable formDiagnosing a full disk or planning a deployment
du -sh <dir>Show total size of a directoryFinding what’s eating your disk space
free -hShow RAM and swap usageDiagnosing out-of-memory conditions or sizing a server
uptimeShow how long the system has been running and load averagesQuick health check — high load averages signal CPU pressure
whoamiPrint the current user’s nameConfirming which user you’re acting as, especially after su
which <cmd>Show the full path to an executableVerifying which version of a tool the shell is resolving
historyList previously run commandsRecovering 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 .