Linux Commands Cheat Sheet
The Linux commands developers and administrators actually use: files and directories, finding things, grep, sed and awk, permissions, archives, processes, services, networking, SSH and cron. Commands that print text show their real output from GNU coreutils, grep, sed and gawk; commands that report on your machine are explained instead, because their output depends on it.
By Bogdan SanduUpdated December 2, 2026
Checked against GNU coreutils and Ubuntu 24.04
chmod calculator
Tick the permissions or type a mode such as 755, u=rwx,go=rx or -rw-r--r--, and get every other form plus the command.
Cron expression explainer
Paste a crontab line, with or without the command, and read when it runs, with the next five run times in UTC.
Five fields: minute, hour, day of month, month, day of week. Lists (1,15), ranges (1-5), steps (*/10) and names (mon, jan) work, as do @daily, @hourly and the other shortcuts.
Getting Help
Read the manual
man, --help and friends
Manual sections: 1 for commands, 5 for config file formats, 8 for admin commands. man -k word is the same as apropos.
$ man ls # full manual page; q quits, / searches
$ ls --help # short usage for GNU tools
$ man 5 crontab # section 5: file formats
$ apropos compress # search manual page titles
$ tldr tar # community examples, needs the tldr clientFind out what a command is
type tells you whether a name is an alias, a shell builtin, a function or a file. command -v is the portable way to test for a program in scripts.
$ type ls cd ll
$ which python3
$ command -v git || echo "git is not installed"Shortcuts in the shell
Keys that save the most time
| Keys | Does |
|---|---|
Tab | Complete a command, file or option |
Ctrl+R | Search the command history; press again for older matches |
Ctrl+C | Stop the running command |
Ctrl+D | End input, or log out of an empty prompt |
Ctrl+Z | Suspend the running command; fg resumes it |
Ctrl+A and Ctrl+E | Start and end of the line |
Ctrl+W and Ctrl+U | Delete the word before the cursor, or the whole line before it |
Ctrl+L | Clear the screen |
!! | Repeat the last command, as in sudo !! |
!$ and Alt+. | The last argument of the previous command |
Files & Directories
Create, copy, move, delete
Create files and directories
$ mkdir -p app/src/utils # -p creates parents and does not fail if it exists
$ touch app/README.md # create an empty file, or update its timestamp
$ find app | sortapp
app/README.md
app/src
app/src/utilsCopy and move
$ cp notes.txt notes.bak # copy a file
$ cp -r src/ backup/ # copy a directory and everything in it
$ cp -a src/ backup/ # archive mode: keep permissions, owners and times
$ mv draft.txt final.txt # rename
$ mv *.log logs/ # move several files into a directory
$ cp -i a.txt b.txt # ask before overwritingDelete, carefully
There is no recycle bin: rm is permanent. Run ls with the same pattern first, and be extra careful with variables in rm -rf "$DIR"/, because an empty variable turns it into rm -rf /.
$ rm old.txt # remove a file
$ rm -i *.tmp # ask for each file
$ rmdir empty-dir # remove a directory only if it is empty
$ rm -r build/ # remove a directory and its contents
$ rm -rf build/ # same, without prompts or errorsLinks
Symbolic and hard links
A symbolic link breaks if the target is removed; a hard link keeps the data alive until every name is gone. Hard links cannot cross file systems or point to directories.
$ ln -s /opt/app/releases/v2 current # symbolic link, like a shortcut
$ ln -sfn /opt/app/releases/v3 current # point an existing link somewhere else
$ readlink -f current # where it really points
$ ln data.db data-hardlink.db # hard link: a second name for the same fileViewing Files
Read files
First lines of a file
head -n 20 is the default-sized peek; head -c 100 takes bytes instead of lines.
$ head -n 2 logs/app.log2026-12-01 10:02:11 INFO api started on :8080
2026-12-01 10:05:43 WARN slow query 1.8s usersLast lines, and following a log live
tail -f file keeps following a file as it grows, which is how you watch a log live; Ctrl+C stops it. tail -F also survives log rotation.
$ tail -n 1 logs/app.log2026-12-01 10:11:47 INFO GET /orders 200Count lines, words and bytes
wc -w counts words and wc -c bytes. less file pages through a file: Space for the next page, / to search, q to quit.
$ wc -l logs/app.log users.csv 6 logs/app.log
6 users.csv
12 totalPrint a file with line numbers
$ cat -n project/src/util.py 1 def add(a, b):
2 return a + bFind out what kind of file it is
file reads the content, not the extension, so it tells a renamed PNG from a real text file.
$ file project/README.mdproject/README.md: ASCII textCompare files
diff -u prints a unified diff, the format git and patch use. Lines with - were removed, lines with + were added.
$ printf 'a\nb\nc\n' > old.txt
$ printf 'a\nB\nc\nd\n' > new.txt
$ diff -u old.txt new.txt--- old.txt 2026-12-02 16:12:55.098387300 +0000
+++ new.txt 2026-12-02 16:12:55.099360500 +0000
@@ -1,3 +1,4 @@
a
-b
+B
c
+dFinding Files
find
By name, type, size and age
-mtime +7 means modified more than seven days ago, -mtime -1 within the last day. Quote patterns like "*.py" so the shell does not expand them before find sees them.
$ find . -name "*.py"
$ find . -type d -name src
$ find . -iname "readme*"
$ find . -type f -size +1M
$ find /var/log -name "*.log" -mtime +7
$ find . -type f -emptyRun a command on what you find
{} + passes many files to one command. {} \; runs the command once per file, which is slower.
$ find . -name "*.py" -exec wc -l {} + 1 ./project/src/main.py
2 ./project/src/util.py
3 totalDelete what you find, safely
$ find /tmp/cache -type f -mtime +30 -print # look first
$ find /tmp/cache -type f -mtime +30 -delete # then delete
$ find . -name "*.tmp" -print0 | xargs -0 rm -f # safe with spaces in namesFaster alternatives
| Tool | Use |
|---|---|
locate name | Searches a prebuilt database; update it with sudo updatedb |
fd pattern | A faster find with simpler syntax, from your package manager |
which cmd | Where a command lives on your PATH |
grep: Search Text
Search with grep
Lines that contain a word
$ grep ERROR logs/app.log2026-12-01 10:06:02 ERROR db timeout after 30s
2026-12-01 10:09:30 ERROR payment declined order=8812Count matches
-c counts matching lines, not matches; two matches on one line count once.
$ grep -c ERROR logs/app.log2Ignore case and show line numbers
$ grep -n -i "slow" logs/app.log2:2026-12-01 10:05:43 WARN slow query 1.8s usersLines that do not match
$ grep -v INFO logs/app.log2026-12-01 10:05:43 WARN slow query 1.8s users
2026-12-01 10:06:02 ERROR db timeout after 30s
2026-12-01 10:09:30 ERROR payment declined order=8812Search a whole project
-r searches directories recursively. ripgrep (rg) does the same, faster, and skips files listed in .gitignore.
$ grep -rn "def " project/project/src/util.py:1:def add(a, b):Only the names of matching files
$ grep -rl "print" project/ --include="*.py"project/src/main.pyMatch one pattern or another
-E enables extended regular expressions, so | means or and + and ? work without backslashes.
$ grep -E "WARN|ERROR" logs/app.log2026-12-01 10:05:43 WARN slow query 1.8s users
2026-12-01 10:06:02 ERROR db timeout after 30s
2026-12-01 10:09:30 ERROR payment declined order=8812Print only the part that matched
$ grep -o "order=[0-9]*" logs/app.logorder=8812Show lines around each match
-A adds lines after, -B lines before and -C lines on both sides.
$ grep -A1 "slow query" logs/app.log2026-12-01 10:05:43 WARN slow query 1.8s users
2026-12-01 10:06:02 ERROR db timeout after 30ssed & awk
sed: edit streams
Replace text
s/old/new/ replaces the first match on each line; add g for all of them.
$ sed 's/INFO/info/' logs/app.log | head -n 12026-12-01 10:02:11 info api started on :8080Print a range of lines
$ sed -n '2,3p' logs/app.log2026-12-01 10:05:43 WARN slow query 1.8s users
2026-12-01 10:06:02 ERROR db timeout after 30sDelete matching lines
$ sed '/INFO/d' logs/app.log2026-12-01 10:05:43 WARN slow query 1.8s users
2026-12-01 10:06:02 ERROR db timeout after 30s
2026-12-01 10:09:30 ERROR payment declined order=8812Edit a file in place
-i changes the file itself; -i.bak keeps a backup copy. On macOS, BSD sed needs sed -i '' instead of sed -i.
$ sed -i 's/localhost/db.internal/g' config.ini
$ sed -i.bak 's/debug=true/debug=false/' app.confawk: work with columns
Print columns
-F, sets the field separator, $1 is the first column and NR > 1 skips the header line.
$ awk -F, 'NR > 1 { print $1, $3 }' users.csvann 7200
bob 5100
cy 6800
dee 4900
eve 5600Filter rows by a column
$ awk -F, '$2 == "dev" { print $1 }' users.csvann
cySum a column
The END block runs once after the last line.
$ awk -F, 'NR > 1 { sum += $3 } END { print "total", sum }' users.csvtotal 29600Group and count
awk arrays are hashes, so this computes the count and average salary per department in one pass.
$ awk -F, 'NR > 1 { n[$2]++; s[$2] += $3 } END { for (d in n) print d, n[d], s[d] / n[d] }' users.csv | sortdev 2 7000
ops 2 5350
sales 1 4900sort, uniq, cut & Friends
Sort and count
Sort lines
sort -r reverses, sort -n sorts numbers by value, sort -h understands sizes like 2K and 1G, and sort -u drops duplicates.
$ sort fruits.txtapple
apple
apple
banana
banana
cherrySort a CSV by a numeric column
tail -n +2 skips the header. -t, sets the separator and -k3,3nr sorts by the third field only, as numbers, largest first.
$ tail -n +2 users.csv | sort -t, -k3,3nrann,dev,7200
cy,dev,6800
eve,ops,5600
bob,ops,5100
dee,sales,4900Count how often each line appears
uniq only collapses neighbouring duplicates, so always sort first. This pipeline is the classic frequency count.
$ sort fruits.txt | uniq -c | sort -rn 3 apple
2 banana
1 cherryCut and transform
Take columns with cut
-d sets the delimiter and -f picks fields. For columns separated by runs of spaces, use awk instead.
$ cut -d, -f1,3 users.csv | head -n 3name,salary
ann,7200
bob,5100Translate or delete characters with tr
tr -d '\r' strips Windows line endings, and tr -s ' ' squeezes repeated spaces.
$ echo "Hello, World" | tr 'a-z' 'A-Z'HELLO, WORLDAlign columns for reading
$ column -t -s, users.csvname dept salary
ann dev 7200
bob ops 5100
cy dev 6800
dee sales 4900
eve ops 5600Save output and see it at the same time
tee writes to a file and passes the same data on. tee -a appends instead of overwriting.
$ grep ERROR logs/app.log | tee errors.txt | wc -l2Pipes & Redirection
Redirection
Send output to files
Order matters: > file 2>&1 sends both to the file, while 2>&1 > file still sends errors to the terminal.
| Syntax | Does |
|---|---|
cmd > file | Write stdout to file, replacing it |
cmd >> file | Append stdout to file |
cmd 2> errors.log | Write stderr to a file |
cmd > all.log 2>&1 | Both stdout and stderr to one file |
cmd &> all.log | The same, in Bash |
cmd > /dev/null 2>&1 | Throw all output away |
cmd < input.txt | Read stdin from a file |
cmd1 | cmd2 | Pipe stdout of cmd1 into cmd2 |
cmd1 |& cmd2 | Pipe stdout and stderr, in Bash |
Use a command's output inside another command
$(...) runs the command and puts its output in place. Quote it, as here, so spaces in the output do not split it into several arguments.
$ echo "src holds $(ls project/src | wc -l) files"src holds 2 filesFeed a string to stdin
<<< is a here-string in Bash. For several lines, use a heredoc: cat <<'EOF' ... EOF.
$ wc -w <<< "three little words"3xargs
Turn input lines into arguments
-n 1 runs the command once per input item. -P 4 runs four at a time in parallel, and -I{} puts each item where {} appears in the command.
$ printf 'one\ntwo\nthree\n' | xargs -n 1 echo itemitem one
item two
item threeUse xargs safely with file names
-print0 and -0 separate names with a null byte, so names with spaces or newlines do not break.
$ find . -name "*.log" -print0 | xargs -0 grep -l ERROR./logs/app.logPermissions & Ownership
chmod
Numeric modes
Each digit adds read 4, write 2 and execute 1: 7 = 4+2+1 = rwx, 5 = 4+1 = r-x. On a directory, x means you can enter it and r that you can list it.
| Mode | Owner | Group | Others | Typical use |
|---|---|---|---|---|
755 | rwx | r-x | r-x | Scripts, programs, directories |
644 | rw- | r-- | r-- | Ordinary files |
700 | rwx | --- | --- | Private directories, ~/.ssh |
600 | rw- | --- | --- | Private keys, secrets |
775 | rwx | rwx | r-x | Shared project directories |
777 | rwx | rwx | rwx | Almost never a good idea |
Change permissions
Symbolic modes use u, g, o and a for user, group, others and all, with + to add, - to remove and = to set exactly.
$ chmod +x deploy.sh # make executable for everyone
$ chmod u+x,go-w deploy.sh # owner gets x, group and others lose w
$ chmod 600 ~/.ssh/id_ed25519 # numeric form
$ chmod -R g+rw shared/ # recursive
$ find site -type d -exec chmod 755 {} + # directories only
$ find site -type f -exec chmod 644 {} + # files onlyChange owner and group
$ sudo chown ann report.txt
$ sudo chown ann:devs report.txt
$ sudo chown -R www-data:www-data /var/www/site
$ sudo chgrp devs shared/Special bits and umask
| Setting | Does |
|---|---|
chmod u+s file | setuid: runs as the file's owner, like passwd |
chmod g+s dir | setgid: new files inherit the directory's group |
chmod +t dir | sticky: only owners can delete their files, like /tmp |
umask 022 | New files get 644 and directories 755 |
umask 077 | New files are private to you |
Archives & Compression
tar
Create, list and extract
c creates, t lists, x extracts, z uses gzip and f names the archive file. Modern GNU tar detects the compression when extracting, so tar -xf file.tar.gz is enough.
$ tar -czf project.tar.gz project/
$ tar -tzf project.tar.gz | sortproject/
project/README.md
project/docs/
project/docs/notes.md
project/src/
project/src/main.py
project/src/util.pyThe tar commands to remember
| Command | Does |
|---|---|
tar -czf out.tar.gz dir/ | Create a gzip archive |
tar -cJf out.tar.xz dir/ | Create an xz archive, smaller and slower |
tar --zstd -cf out.tar.zst dir/ | Create a zstd archive, fast with a good ratio |
tar -xf archive.tar.gz | Extract here |
tar -xf archive.tar.gz -C /opt/app | Extract into a directory |
tar -tf archive.tar.gz | List the contents |
tar -czf out.tar.gz --exclude=node_modules dir/ | Leave something out |
Single files and zip
gzip, xz and zip
$ gzip big.log # big.log becomes big.log.gz
$ gunzip big.log.gz # and back
$ zcat big.log.gz | grep ERROR # read without extracting
$ xz -9 dump.sql # better compression than gzip
$ zip -r site.zip site/ # zip for people on Windows and macOS
$ unzip site.zip -d site-copyDisk Usage
Space
Free space and folder sizes
du -sh * sizes everything in the current directory. ncdu, if installed, browses sizes interactively.
$ df -h # free space per file system
$ df -h /var # the file system /var lives on
$ du -sh project/ # total size of a directory
$ du -h --max-depth=1 /var | sort -h # size of each subdirectory
$ lsblk # disks and partitionsFind the biggest files
-xdev keeps find on one file system, so it does not wander into /proc or mounted network drives.
$ find / -xdev -type f -size +500M -exec ls -lh {} + 2>/dev/null
$ du -ah /var/log | sort -rh | head -n 10Processes
See what is running
List and find processes
In top, P sorts by CPU, M by memory, k kills a process and q quits.
$ ps aux # every process, BSD style
$ ps -ef --forest # every process with its parent tree
$ ps aux --sort=-%mem | head # the biggest memory users
$ pgrep -a nginx # PIDs and command lines matching a name
$ top # live view; htop is friendlier if installedWho is using a port or a file
$ sudo ss -tlnp # listening TCP ports and their processes
$ sudo lsof -i :8080 # what has port 8080 open
$ sudo lsof /var/log/app.log # who has this file openStop processes
Signals
Send SIGTERM first and give the program a few seconds to shut down cleanly; SIGKILL cannot be caught, so files and sockets may be left behind.
$ kill 4321 # ask nicely: SIGTERM
$ kill -9 4321 # force: SIGKILL, no cleanup
$ pkill -f "python app.py"
$ killall nodeJobs
Run things in the background
For anything long-running on a server, a tmux session or a systemd service is more reliable than nohup.
| Command | Does |
|---|---|
cmd & | Start in the background |
Ctrl+Z then bg | Suspend a running command, then continue it in the background |
jobs | List background jobs |
fg %1 | Bring job 1 to the foreground |
nohup cmd > out.log 2>&1 & | Keep running after you log out |
disown | Detach a running job from the shell |
System Information
About this machine
Kernel, distribution and uptime
The three load averages are for 1, 5 and 15 minutes. A load higher than the number of CPU cores means work is waiting.
$ uname -a # kernel and architecture
$ cat /etc/os-release # distribution name and version
$ hostnamectl # hostname, OS and kernel on systemd systems
$ uptime # how long it has run, and load averagesMemory, CPU and hardware
In free, look at the available column, not free: Linux uses spare memory as cache and gives it back when programs need it.
$ free -h # memory and swap
$ nproc # number of CPU cores
$ lscpu # CPU details
$ lspci; lsusb # PCI and USB devices
$ dmesg -T | tail # recent kernel messagesDates and times
-d parses a date, including relative phrases and @epoch seconds; this is GNU date. timedatectl shows and sets the time zone on systemd systems.
$ date -u -d "2026-12-02 + 30 days" +%F
$ date -u -d @1796256000
$ date -u -d "2026-12-02" +"%A, week %V, day %j"2027-01-01
Thu Dec 3 00:00:00 UTC 2026
Wednesday, week 49, day 336Users & sudo
Who am I
Identity
$ whoami
$ id
$ groups
$ who # who is logged in
$ last -n 5 # recent loginsManage users
Add users and groups
Without -a, usermod -G replaces every supplementary group the user has. Group changes take effect at the next login, or immediately in a new shell started with newgrp docker.
$ sudo adduser ann # interactive, Debian and Ubuntu
$ sudo useradd -m -s /bin/bash ann # low-level, every distribution
$ sudo passwd ann # set a password
$ sudo usermod -aG docker ann # add to a group; -a appends
$ sudo deluser ann # or userdel -r annRun commands as another user
visudo checks the syntax before saving, so a typo cannot lock you out of sudo.
$ sudo apt update # one command as root
$ sudo -i # a root login shell
$ sudo -u postgres psql # as another user
$ sudo visudo # edit sudo rules safelyPackage Managers
Install software
The same task on each distribution
On Arch, always upgrade the whole system with -Syu; installing after a bare -Sy can leave mismatched libraries.
| Task | Debian, Ubuntu | Fedora, RHEL | Arch |
|---|---|---|---|
| Refresh the package list | sudo apt update | sudo dnf check-update | sudo pacman -Sy |
| Upgrade everything | sudo apt upgrade | sudo dnf upgrade | sudo pacman -Syu |
| Install | sudo apt install nginx | sudo dnf install nginx | sudo pacman -S nginx |
| Remove | sudo apt remove nginx | sudo dnf remove nginx | sudo pacman -R nginx |
| Search | apt search nginx | dnf search nginx | pacman -Ss nginx |
| Show details | apt show nginx | dnf info nginx | pacman -Si nginx |
| Which package owns a file | dpkg -S /usr/bin/curl | rpm -qf /usr/bin/curl | pacman -Qo /usr/bin/curl |
| List installed | apt list --installed | dnf list installed | pacman -Q |
Services & Logs (systemd)
systemctl
Control services
$ sudo systemctl status nginx
$ sudo systemctl restart nginx
$ sudo systemctl reload nginx # reread config without dropping connections
$ sudo systemctl enable --now nginx # start now and at every boot
$ sudo systemctl disable nginx
$ systemctl list-units --failedWrite a service for your own app
After creating or editing a unit file, run sudo systemctl daemon-reload, then enable and start it.
[Unit]
Description=Orders API
After=network-online.target
Wants=network-online.target
[Service]
User=api
WorkingDirectory=/opt/api
ExecStart=/opt/api/bin/server --port 8080
Restart=on-failure
Environment=APP_ENV=production
[Install]
WantedBy=multi-user.targetjournalctl
Read logs
$ journalctl -u nginx # one service
$ journalctl -u nginx -f # follow live
$ journalctl -u nginx --since "1 hour ago"
$ journalctl -p err -b # errors since the last boot
$ journalctl --disk-usage
$ sudo journalctl --vacuum-time=7d # delete older logsNetworking
Interfaces and connections
Addresses, routes and DNS
ifconfig and netstat come from the old net-tools package, which many distributions no longer install. ip and ss replace them.
$ ip -br addr # interfaces and their IP addresses, one per line
$ ip route # routing table and default gateway
$ resolvectl status # DNS servers on systemd-resolved systems
$ cat /etc/resolv.conf # DNS servers everywhere else
$ hostname -I # this machine's IP addressesIs it reachable
$ ping -c 4 example.com
$ traceroute example.com # or mtr for a live view
$ dig +short example.com A
$ dig +short example.com MX
$ nc -zv db.internal 5432 # can I open a TCP connection to this portOpen ports
Allow SSH in the firewall before you enable it on a remote server, or you lock yourself out.
$ sudo ss -tulpn # listening TCP and UDP ports with processes
$ ss -tn state established
$ sudo ufw allow 22/tcp # Ubuntu firewall
$ sudo ufw enable
$ sudo firewall-cmd --add-service=https --permanent # Fedora and RHELHTTP from the command line
curl
-s hides the progress bar and -S still shows errors. The last line prints only the status code and total time, which makes a quick health check.
$ curl -sS https://api.github.com/zen
$ curl -I https://example.com # headers only
$ curl -L -o file.zip https://example.com/f # follow redirects, save to a file
$ curl -X POST -H "Content-Type: application/json" -d '{"name":"ann"}' https://httpbin.org/post
$ curl -w '%{http_code} %{time_total}s\n' -o /dev/null -s https://example.comwget
$ wget https://example.com/file.iso
$ wget -c https://example.com/file.iso # resume a broken download
$ wget -r -np -k https://example.com/docs/ # mirror a section of a siteSSH & File Transfer
Connect
Keys and logins
Ed25519 keys are short, fast and the default choice today. Keep the private key at 600 permissions; ssh refuses keys that others can read.
$ ssh-keygen -t ed25519 -C "ann@laptop"
$ ssh-copy-id ann@server.example.com
$ ssh ann@server.example.com
$ ssh -p 2222 ann@server.example.com
$ ssh ann@server 'df -h /' # run one command remotelySave hosts in ~/.ssh/config
Now ssh prod, scp file prod: and rsync ... prod: all use those settings.
Host prod
HostName 203.0.113.10
User deploy
Port 2222
IdentityFile ~/.ssh/id_ed25519
Host *
ServerAliveInterval 60Tunnels
$ ssh -L 5433:localhost:5432 prod # local port 5433 reaches the server's database
$ ssh -R 8080:localhost:3000 prod # the server's port 8080 reaches your laptop
$ ssh -J bastion prod # jump through a bastion hostCopy files
scp and rsync
rsync copies only what changed and can resume. A trailing slash on the source copies its contents rather than the folder itself. --delete removes files on the target that are gone from the source, so try it with -n first.
$ scp report.pdf prod:/tmp/
$ scp -r prod:/var/log/nginx ./nginx-logs
$ rsync -avz --progress site/ prod:/var/www/site/
$ rsync -avz --delete site/ prod:/var/www/site/
$ rsync -avzn --delete site/ prod:/var/www/site/ # dry run firstEnvironment & PATH
Variables
Set, read and export
Only exported variables reach child processes. A VAR=value cmd prefix sets it for that one command. ${VAR:-x} substitutes x when VAR is unset or empty.
$ NAME=world
$ echo "Hello, $NAME"
$ export APP_ENV=staging
$ env | grep '^APP_ENV='
$ APP_ENV=test bash -c 'echo $APP_ENV'
$ echo "${MISSING:-default value}"Hello, world
APP_ENV=staging
test
default valueAdd a directory to PATH for good
Run source ~/.bashrc or open a new terminal to apply it. On zsh, the default on macOS, use ~/.zshrc. echo $PATH | tr ':' '\n' lists the PATH one directory per line.
export PATH="$HOME/.local/bin:$PATH"
alias ll='ls -lah'
alias gs='git status'Scheduling with cron
crontab
Edit and list your jobs
$ crontab -e # edit
$ crontab -l # list
$ sudo crontab -u www-data -lCron syntax
Cron runs with a minimal PATH and no terminal, so use full paths and redirect output: ... >> /var/log/backup.log 2>&1. The builder above the sections explains any expression.
# minute hour day-of-month month day-of-week command
*/5 * * * * /opt/app/bin/poll # every 5 minutes
0 2 * * * /opt/app/bin/backup # 02:00 every day
30 8 * * 1-5 /opt/app/bin/report # 08:30 Monday to Friday
0 0 1 * * /opt/app/bin/invoice # midnight on the 1st
@reboot /opt/app/bin/start # once at bootChecksums & Encoding
Hashes and encodings
Hash a file and check a download
Plain sha256sum file prints the hash, two spaces and the name. --tag writes the labelled BSD format shown here, which macOS shasum also understands. Compare the hash with the one the publisher lists. MD5 and SHA-1 are fine for spotting corruption but not for security.
$ printf 'hello\n' > hello.txt
$ sha256sum --tag hello.txt | tee hello.txt.sha256
$ sha256sum -c hello.txt.sha256SHA256 (hello.txt) = 5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03
hello.txt: OKBase64 and random values
The last line confirms 16 random bytes become 32 hex characters. openssl rand -hex 16 does the same in one command.
$ echo -n 'user:pass' | base64
$ echo 'dXNlcjpwYXNz' | base64 -d; echo
$ head -c 16 /dev/urandom | od -An -tx1 | tr -d ' \n' | wc -cdXNlcjpwYXNz
user:pass
32Troubleshooting
Error messages
What the common errors mean
| Message | Usually means | Try |
|---|---|---|
command not found | Not installed, or not on PATH | command -v name, install the package, check PATH |
Permission denied | No read, write or execute permission | ls -l, chmod +x, or sudo if it is a system file |
No such file or directory on a script that exists | A wrong shebang or Windows line endings | head -1 script, sed -i 's/\r$//' script |
No space left on device | The disk or its inodes are full | df -h, df -i, du -sh /var/* |
Address already in use | Another process has the port | sudo ss -tlnp | grep :8080 |
Connection refused | Nothing listens on that port, or a firewall rejects it | ss -tlnp on the server, check the firewall |
Killed | The kernel's out-of-memory killer stopped the process | dmesg -T | grep -i oom, add memory or swap |
Too many open files | The process hit its file descriptor limit | ulimit -n, raise LimitNOFILE in the systemd unit |
Read-only file system | The disk was remounted read-only after errors | dmesg -T, check the disk, then fsck |
Quick health check
Five commands when a server is slow
$ uptime # load
$ free -h # memory and swap
$ df -h # disk space
$ top -o %CPU # who uses the CPU
$ journalctl -p err --since "1 hour ago"Nothing matches. Try a single word.
What Is a Linux Commands Cheat Sheet
A Linux commands cheat sheet is a short reference to the commands you type in a Linux terminal, grouped by task so you can find how to search a folder, change permissions, unpack an archive or restart a service without reading a manual page first. People also search for basic Linux commands, Linux terminal commands or a Linux command line cheat sheet; they usually need it on a new server, in a Docker container or while following a deployment guide.
This one has 23 sections and 90 rows. The text processing examples, from find and grep to sed, awk, sort and tar, were run on sample files and the output under them is what the GNU tools printed. Commands that report on your own machine, such as df, ps, ip or systemctl, have explanations instead of sample output, because their output is different on every system. The package manager table covers Debian and Ubuntu, Fedora and RHEL, and Arch.
How It Differs From man Pages
Manual pages document every option of one command. This page goes the other way: it starts from the job, such as finding the biggest files or checking which process owns a port, and shows the shortest command that does it, with the options you will actually use and the mistake that usually goes with it. When you need more, man command and command --help are covered in the first section.
What This Linux Commands Cheat Sheet Covers
- Basics: getting help and shell shortcuts, navigating and listing, files and directories, viewing and comparing files and finding files.
- Text: grep, sed and awk, sort, uniq, cut and tr and pipes, redirection and xargs.
- System: permissions, archives, disk usage, processes, system information, users and sudo, package managers and systemd services and logs.
- Network: networking and curl and SSH, scp and rsync.
- Shell: environment variables and PATH, cron and checksums and base64.
- Help: common errors and a quick health check.
Most Used Linux Commands
| Task | Command |
|---|---|
| Where am I | pwd |
| List files with details | ls -lah |
| Change directory | cd /path, cd .., cd - |
| Make a directory tree | mkdir -p a/b/c |
| Copy a folder | cp -r src dst |
| Move or rename | mv old new |
| Delete a folder | rm -r folder |
| Read a file | less file |
| Follow a log | tail -f file.log |
| Find files by name | find . -name "*.log" |
| Search text in files | grep -rn "text" . |
| Replace text in a file | sed -i 's/old/new/g' file |
| Make a script executable | chmod +x script.sh |
| Change the owner | sudo chown user:group file |
| Pack a folder | tar -czf out.tar.gz folder/ |
| Unpack an archive | tar -xf file.tar.gz |
| Disk space | df -h |
| Folder size | du -sh folder |
| Running processes | ps aux, top |
| Stop a process | kill PID |
| Listening ports | sudo ss -tlnp |
| Service status | systemctl status name |
| Service logs | journalctl -u name -f |
| Install a package | sudo apt install name |
| Connect to a server | ssh user@host |
| Copy to a server | rsync -avz dir/ host:dir/ |
| Download a file | curl -LO URL |
| Schedule a job | crontab -e |
How the Linux Command Line Works
When you type a command, the shell, usually Bash on Linux servers and zsh on macOS, splits the line into words, expands variables and wildcards such as *.log, and runs the program it finds on your PATH. Most of the commands on this page are small programs from the GNU core utilities, grep, sed, findutils and tar, plus tools from systemd and OpenSSH, and they follow the same Unix idea: each does one job, reads text and writes text. The GNU coreutils manual documents every option of the core tools.
That idea is what makes pipes powerful. sort fruits.txt | uniq -c | sort -rn chains three small tools into a frequency count that no single one of them could do. Learning a dozen text tools well and how to connect them with |, > and xargs pays off more than memorising rarely used options. For scripting beyond one-liners, the Bash cheat sheet covers variables, loops, functions and error handling, and the regex cheat sheet the patterns grep, sed and awk accept.
Where You Will Use These Commands
Almost every server, container and cloud VM runs Linux, so these commands follow you from a laptop terminal into Docker containers, Kubernetes pods and CI jobs. They are the daily toolkit of DevOps work: reading logs, checking disk and memory, restarting services and copying files during app deployment. On a remote server, run long jobs inside tmux so they survive a dropped SSH connection, and edit files with Vim, which is installed almost everywhere.
GNU Linux and macOS Differences
| Task | Linux (GNU) | macOS (BSD) |
|---|---|---|
| Edit in place with sed | sed -i 's/a/b/' f | sed -i '' 's/a/b/' f |
| Date arithmetic | date -d "+1 day" | date -v+1d |
| File details | stat -c '%s %n' f | stat -f '%z %N' f |
| Services | systemctl | launchctl, brew services |
| Packages | apt, dnf, pacman | brew |
| Clipboard | wl-copy, xclip | pbcopy |
Common Linux Command Line Mistakes
- rm -rf with an unquoted or empty variable. Quote paths and use
${DIR:?}so the command fails when the variable is empty. - chmod 777 to fix a permission error. It hides the real problem and lets anyone change the file; fix the owner or give the group access instead.
- Redirecting into the file you are reading.
sort f > fempties the file before sort reads it; write to a new file, or usesort -o f f. - Parsing ls output in scripts. File names can contain spaces and newlines; use globs or
find -print0. - Forgetting sudo is per command.
sudo echo x > /etc/filefails because the redirection runs as you; useecho x | sudo tee /etc/file. - Editing crontab without full paths. Cron has a minimal PATH, so commands that work in your terminal fail silently.
How to Get Comfortable in the Terminal
Learn the Movement Keys First
Tab completion, Ctrl+R history search and the up arrow save more time than any single command. Then spend a week doing your usual file work in the terminal: navigating, copying, searching with grep and find. Read a man page each time you use a new option, and you will remember it.
Then Learn Text Processing
grep, sed, awk, sort, uniq and cut turn log files and CSV exports into answers in seconds. Practise on your own logs, build pipelines one command at a time, and keep the ones you reuse as shell aliases or small scripts in a dotfiles repository. When a pipeline grows past a line or two, move it into a script, or into Python or Perl.
How This Linux Commands Cheat Sheet Is Maintained
The examples with output were run by a script against a set of sample files, with GNU coreutils, grep, sed, gawk, findutils and tar, in UTC with the C.UTF-8 locale, and the output was copied under each command unchanged. Options and behaviour were checked against the GNU manuals and Ubuntu 24.04 manual pages. Commands whose output depends on the machine are explained rather than shown.
Sources: the GNU coreutils, grep, sed, gawk, findutils and tar manuals, the Ubuntu 24.04 manual pages, the systemd and OpenSSH documentation, and the crontab(5) manual page.
Linux Command Questions People Actually Ask
What are the basic Linux commands every beginner should know?
Start with pwd, ls and cd to move around, mkdir, cp, mv and rm to manage files, cat, less, head and tail to read them, grep and find to search, chmod for permissions, sudo to run admin commands, and man or --help to read the documentation for any of them.
How do I find a file by name in Linux?
Use find with -name, for example find . -name "*.conf" searches the current directory and everything under it. Add -type f for files only, -iname to ignore case, and -mtime or -size to filter by age or size. locate is faster but searches a database you refresh with sudo updatedb.
How do I search for text inside files?
Use grep: grep -rn "text" folder/ searches every file under the folder and prints the file name and line number of each match. Add -i to ignore case, -l to list only file names, -E for extended regular expressions and --include="*.py" to limit the file types.
What does chmod 755 mean?
chmod 755 gives the owner read, write and execute permission, and the group and everyone else read and execute. Each digit adds read 4, write 2 and execute 1, so 7 is rwx and 5 is r-x. It is the usual mode for scripts, programs and directories; ordinary files usually get 644.
How do I see which process is using a port?
Run sudo ss -tlnp, which lists listening TCP ports with the process and PID that owns each one, or sudo lsof -i :8080 for a single port. Then stop the process with kill and its PID, or restart the service that owns it with systemctl.
How do I check disk space in Linux?
df -h shows free space on every mounted file system in human-readable sizes. du -sh folder shows how much a folder uses, and du -h --max-depth=1 /var | sort -h lists the biggest subfolders. If df shows space but writes fail, check inodes with df -i.
What is the difference between apt, dnf and pacman?
They are the package managers of different distribution families: apt for Debian and Ubuntu, dnf for Fedora, RHEL, Rocky and Alma, and pacman for Arch. They do the same jobs with different syntax, and the package manager table on this page shows the matching commands side by side.
How do I run a command in the background?
Add & at the end to start it in the background, or press Ctrl+Z and then type bg for a command that is already running. jobs lists background jobs and fg brings one back. To keep a command running after you log out, use nohup, a tmux session or a systemd service.
Are these commands the same on macOS?
Most of them work, because macOS is a Unix system, but it ships BSD versions of tools such as sed, date, find and stat with different options. sed -i needs an argument on macOS, date -d does not exist and systemctl, apt and journalctl are Linux only. Installing GNU coreutils with Homebrew gives you the Linux behaviour.
Can I download this Linux commands cheat sheet as a PDF?
Yes. Use your browser's print command and choose Save as PDF. The print layout keeps every command, output and explanation and leaves out the search box, navigation and tools. Run a search first to print only the rows that are still visible.