Contents

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.

ReadWriteExecute Owner Group Others
Result

    

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.

Schedule

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 client

Find 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

KeysDoes
TabComplete a command, file or option
Ctrl+RSearch the command history; press again for older matches
Ctrl+CStop the running command
Ctrl+DEnd input, or log out of an empty prompt
Ctrl+ZSuspend the running command; fg resumes it
Ctrl+A and Ctrl+EStart and end of the line
Ctrl+W and Ctrl+UDelete the word before the cursor, or the whole line before it
Ctrl+LClear 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/utils

Copy 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 overwriting

Delete, 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 errors

Links

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 file

Viewing 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 users

Last 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 200

Count 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 total

Print a file with line numbers

$ cat -n project/src/util.py     1	def add(a, b):
     2	    return a + b

Find 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 text

Compare 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
+d

Finding 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 -empty

Run 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 total

Delete 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 names

Faster alternatives

ToolUse
locate nameSearches a prebuilt database; update it with sudo updatedb
fd patternA faster find with simpler syntax, from your package manager
which cmdWhere 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=8812

Count matches

-c counts matching lines, not matches; two matches on one line count once.

$ grep -c ERROR logs/app.log2

Ignore case and show line numbers

$ grep -n -i "slow" logs/app.log2:2026-12-01 10:05:43 WARN  slow query 1.8s users

Lines 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=8812

Search 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.py

Match 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=8812

Print only the part that matched

$ grep -o "order=[0-9]*" logs/app.logorder=8812

Show 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 30s

sed & 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 :8080

Print 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 30s

Delete 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=8812

Edit 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.conf

awk: 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 5600

Filter rows by a column

$ awk -F, '$2 == "dev" { print $1 }' users.csvann
cy

Sum a column

The END block runs once after the last line.

$ awk -F, 'NR > 1 { sum += $3 } END { print "total", sum }' users.csvtotal 29600

Group 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 4900

sort, 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
cherry

Sort 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,4900

Count 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 cherry

Cut 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,5100

Translate 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, WORLD

Align columns for reading

$ column -t -s, users.csvname  dept   salary
ann   dev    7200
bob   ops    5100
cy    dev    6800
dee   sales  4900
eve   ops    5600

Save 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 -l2

Pipes & 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.

SyntaxDoes
cmd > fileWrite stdout to file, replacing it
cmd >> fileAppend stdout to file
cmd 2> errors.logWrite stderr to a file
cmd > all.log 2>&1Both stdout and stderr to one file
cmd &> all.logThe same, in Bash
cmd > /dev/null 2>&1Throw all output away
cmd < input.txtRead stdin from a file
cmd1 | cmd2Pipe stdout of cmd1 into cmd2
cmd1 |& cmd2Pipe 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 files

Feed a string to stdin

<<< is a here-string in Bash. For several lines, use a heredoc: cat <<'EOF' ... EOF.

$ wc -w <<< "three little words"3

xargs

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 three

Use 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.log

Permissions & 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.

ModeOwnerGroupOthersTypical use
755rwxr-xr-xScripts, programs, directories
644rw-r--r--Ordinary files
700rwx------Private directories, ~/.ssh
600rw-------Private keys, secrets
775rwxrwxr-xShared project directories
777rwxrwxrwxAlmost 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 only

Change 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

SettingDoes
chmod u+s filesetuid: runs as the file's owner, like passwd
chmod g+s dirsetgid: new files inherit the directory's group
chmod +t dirsticky: only owners can delete their files, like /tmp
umask 022New files get 644 and directories 755
umask 077New 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.py

The tar commands to remember

CommandDoes
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.gzExtract here
tar -xf archive.tar.gz -C /opt/appExtract into a directory
tar -tf archive.tar.gzList 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-copy

Disk 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 partitions

Find 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 10

Processes

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 installed

Who 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 open

Stop 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 node

Jobs

Run things in the background

For anything long-running on a server, a tmux session or a systemd service is more reliable than nohup.

CommandDoes
cmd &Start in the background
Ctrl+Z then bgSuspend a running command, then continue it in the background
jobsList background jobs
fg %1Bring job 1 to the foreground
nohup cmd > out.log 2>&1 &Keep running after you log out
disownDetach 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 averages

Memory, 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 messages

Dates 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 336

Users & sudo

Who am I

Identity

$ whoami
$ id
$ groups
$ who            # who is logged in
$ last -n 5      # recent logins

Manage 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 ann

Run 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 safely

Package 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.

TaskDebian, UbuntuFedora, RHELArch
Refresh the package listsudo apt updatesudo dnf check-updatesudo pacman -Sy
Upgrade everythingsudo apt upgradesudo dnf upgradesudo pacman -Syu
Installsudo apt install nginxsudo dnf install nginxsudo pacman -S nginx
Removesudo apt remove nginxsudo dnf remove nginxsudo pacman -R nginx
Searchapt search nginxdnf search nginxpacman -Ss nginx
Show detailsapt show nginxdnf info nginxpacman -Si nginx
Which package owns a filedpkg -S /usr/bin/curlrpm -qf /usr/bin/curlpacman -Qo /usr/bin/curl
List installedapt list --installeddnf list installedpacman -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 --failed

Write a service for your own app

After creating or editing a unit file, run sudo systemctl daemon-reload, then enable and start it.

/etc/systemd/system/api.service
[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.target

journalctl

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 logs

Networking

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 addresses

Is 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 port

Open 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 RHEL

HTTP 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.com

wget

$ 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 site

SSH & 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 remotely

Save hosts in ~/.ssh/config

Now ssh prod, scp file prod: and rsync ... prod: all use those settings.

~/.ssh/config
Host prod
    HostName 203.0.113.10
    User deploy
    Port 2222
    IdentityFile ~/.ssh/id_ed25519

Host *
    ServerAliveInterval 60

Tunnels

$ 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 host

Copy 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 first

Environment & 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 value

Add 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.

~/.bashrc
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 -l

Cron 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 boot

Checksums & 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: OK

Base64 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
32

Troubleshooting

Error messages

What the common errors mean

MessageUsually meansTry
command not foundNot installed, or not on PATHcommand -v name, install the package, check PATH
Permission deniedNo read, write or execute permissionls -l, chmod +x, or sudo if it is a system file
No such file or directory on a script that existsA wrong shebang or Windows line endingshead -1 script, sed -i 's/\r$//' script
No space left on deviceThe disk or its inodes are fulldf -h, df -i, du -sh /var/*
Address already in useAnother process has the portsudo ss -tlnp | grep :8080
Connection refusedNothing listens on that port, or a firewall rejects itss -tlnp on the server, check the firewall
KilledThe kernel's out-of-memory killer stopped the processdmesg -T | grep -i oom, add memory or swap
Too many open filesThe process hit its file descriptor limitulimit -n, raise LimitNOFILE in the systemd unit
Read-only file systemThe disk was remounted read-only after errorsdmesg -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"

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


Most Used Linux Commands

TaskCommand
Where am Ipwd
List files with detailsls -lah
Change directorycd /path, cd .., cd -
Make a directory treemkdir -p a/b/c
Copy a foldercp -r src dst
Move or renamemv old new
Delete a folderrm -r folder
Read a fileless file
Follow a logtail -f file.log
Find files by namefind . -name "*.log"
Search text in filesgrep -rn "text" .
Replace text in a filesed -i 's/old/new/g' file
Make a script executablechmod +x script.sh
Change the ownersudo chown user:group file
Pack a foldertar -czf out.tar.gz folder/
Unpack an archivetar -xf file.tar.gz
Disk spacedf -h
Folder sizedu -sh folder
Running processesps aux, top
Stop a processkill PID
Listening portssudo ss -tlnp
Service statussystemctl status name
Service logsjournalctl -u name -f
Install a packagesudo apt install name
Connect to a serverssh user@host
Copy to a serverrsync -avz dir/ host:dir/
Download a filecurl -LO URL
Schedule a jobcrontab -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

TaskLinux (GNU)macOS (BSD)
Edit in place with sedsed -i 's/a/b/' fsed -i '' 's/a/b/' f
Date arithmeticdate -d "+1 day"date -v+1d
File detailsstat -c '%s %n' fstat -f '%z %N' f
Servicessystemctllaunchctl, brew services
Packagesapt, dnf, pacmanbrew
Clipboardwl-copy, xclippbcopy

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 > f empties the file before sort reads it; write to a new file, or use sort -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/file fails because the redirection runs as you; use echo 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.