man linux

Linux Cheatsheet

The Linux commands I lean on to run real servers: moving around the filesystem, reading and slicing logs, processes and systemd, networking and SSH, users and permissions, disks, archives, packages on both Rocky and Ubuntu, firewall and SELinux, scheduled jobs and Bash scripting. Every command has an example you can copy, most show the output to expect, and the tips call out the mistakes that bite in production.

Showing 176 of 176 commands

File operations

13 commands

Create, copy, move, link and delete files without losing permissions or data by accident.

cp -a <src> <dest> beginner Copy recursively in archive mode, keeping permissions, owners, timestamps and symlinks.

Example

bash
cp -av /etc/nginx/ /root/nginx.backup/
'/etc/nginx/' -> '/root/nginx.backup/'
'/etc/nginx/nginx.conf' -> '/root/nginx.backup/nginx.conf'

Tip: -v prints every file copied; drop it for large trees.

cp -r <src> <dest> beginner Copy a directory and everything inside it.

Example

bash
cp -r templates/ /srv/orbit/shared/templates/

Tip: Unlike -a, plain -r does not keep the original owner and timestamps.

cp <file>{,.bak} beginner Make a quick backup copy before editing a file, using brace expansion.

Example

bash
sudo cp /etc/ssh/sshd_config{,.bak}
ls /etc/ssh/sshd_config*
/etc/ssh/sshd_config  /etc/ssh/sshd_config.bak
mv <old> <new> beginner Rename a file or move it to another directory.

Example

bash
mv app.log app-2026-11-04.log
mv -n orbit.conf /etc/orbit/

Tip: -n refuses to overwrite an existing file; -i asks first.

rm -rf <dir> intermediate Delete a directory and its contents without asking.

Example

bash
rm -rf /srv/orbit/releases/2026-10-01

Tip: There is no recycle bin. Run pwd and ls on the exact path first, and never build the path from an unchecked variable.

rm -i <files> beginner Delete files but confirm each one.

Example

bash
rm -i *.tmp
rm: remove regular file 'upload-91.tmp'? y
mkdir -p <path> beginner Create a directory together with any missing parents; no error if it already exists.

Example

bash
mkdir -p /srv/orbit/releases/2026-11-04/logs
touch <file> beginner Create an empty file, or update the timestamp of an existing one.

Example

bash
touch /srv/orbit/shared/maintenance.flag
touch -d '<date>' <file> intermediate Set a file's timestamp to a specific date.

Example

bash
touch -d '2026-01-01 00:00' audit.log
touch -d yesterday build.marker

Tip: Handy for testing find -mtime rules and log rotation.

ln -s <target> <link> intermediate Create a symbolic link that points at another path.

Example

bash
ln -s /var/log/nginx/access.log ~/access.log

Tip: ls -l shows the link and its target as link -> target.

ln -sfn <release> current advanced Repoint an existing symlink in one step: the usual way to switch releases with zero downtime.

Example

bash
ln -sfn /srv/orbit/releases/2026-11-04 /srv/orbit/current
readlink /srv/orbit/current
/srv/orbit/releases/2026-11-04

Tip: -n treats the existing link as a file, so ln replaces it instead of creating a link inside the old target.

ln <file> <hardlink> advanced Create a hard link: a second name for the same inode and the same data.

Example

bash
ln report.csv report-copy.csv
ls -li report*.csv
33575410 -rw-r--r--. 2 jeferson jeferson 812 Nov  4 10:02 report-copy.csv
33575410 -rw-r--r--. 2 jeferson jeferson 812 Nov  4 10:02 report.csv

Tip: Hard links cannot cross filesystems or point at directories.

mktemp intermediate Create a uniquely named temporary file or directory, safe for scripts.

Example

bash
tmp=$(mktemp -d)
echo "$tmp"
/tmp/tmp.Xk3fP0qLnA

Viewing & processing text

19 commands

Read logs and configs, search them, cut columns, count, replace and compare: the core of every troubleshooting session.

cat <file> beginner Print a whole file to the terminal.

Example

bash
cat /etc/os-release
NAME="Rocky Linux"
VERSION="9.7 (Blue Onyx)"
ID="rocky"
PRETTY_NAME="Rocky Linux 9.7 (Blue Onyx)"
less <file> beginner Page through a file. /text searches, n jumps to the next match, G goes to the end, q quits.

Example

bash
less /var/log/messages
# Open already at the end
less +G /var/log/messages

Tip: Press F inside less to follow the file live, and Ctrl+C to stop following.

head -n <n> <file> beginner Show the first lines of a file.

Example

bash
head -n 5 /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
tail -f <file> beginner Keep printing new lines as they are appended to a file.

Example

bash
tail -n 50 -f /var/log/nginx/access.log
10.0.0.12 - - [04/Nov/2026:10:14:02 -0300] "GET /api/health HTTP/1.1" 200 17

Tip: tail -F keeps following even after logrotate replaces the file.

grep -n '<text>' <file> beginner Print the matching lines and their line numbers.

Example

bash
grep -n 'Connection refused' /var/log/orbit/api.log
# Case-insensitive, with 2 lines of context
grep -in -C 2 'timeout' /var/log/orbit/api.log
182:2026-11-04 09:41:07 ERROR db: Connection refused (127.0.0.1:5432)
grep -Rin '<text>' <dir> intermediate Search every file under a directory, case-insensitive, with file names and line numbers.

Example

bash
grep -Rin 'listen 443' /etc/nginx
/etc/nginx/conf.d/orbit.conf:3:    listen 443 ssl;
grep -Ev '<regex>' <file> intermediate Use extended regular expressions and invert the match to hide lines.

Example

bash
# Show a config without comments or blank lines
grep -Ev '^\s*(#|$)' /etc/ssh/sshd_config
Include /etc/ssh/sshd_config.d/*.conf
PermitRootLogin no
PasswordAuthentication no
Subsystem sftp /usr/libexec/openssh/sftp-server
awk '{print $<n>}' <file> advanced Split each line into fields and print, filter or calculate on them.

Example

bash
# User and shell from /etc/passwd
awk -F: '{print $1, $7}' /etc/passwd | head -3
# Requests per HTTP status code
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c
root /bin/bash
bin /sbin/nologin
daemon /sbin/nologin
   1824 200
     37 404
      3 502
sed -n '<from>,<to>p' <file> intermediate Print only a range of lines.

Example

bash
sed -n '40,60p' /etc/nginx/nginx.conf
sed 's/<old>/<new>/g' <file> intermediate Replace text in a stream and print the result; the file itself stays untouched.

Example

bash
sed 's/localhost/127.0.0.1/g' .env.example
sed -i.bak 's/<old>/<new>/' <file> advanced Edit a file in place and keep the original as a .bak copy.

Example

bash
sudo sed -i.bak 's/^#\?PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config
diff /etc/ssh/sshd_config.bak /etc/ssh/sshd_config
40c40
< #PermitRootLogin prohibit-password
---
> PermitRootLogin no

Tip: Without the .bak suffix there is no way back, so keep it until the change is verified.

cut -d<delim> -f<fields> <file> beginner Extract columns from delimiter-separated text.

Example

bash
cut -d: -f1 /etc/passwd | head -3
cut -d, -f2,4 inventory.csv
root
bin
daemon
sort / sort -u beginner Sort lines; -u drops duplicates, -n sorts numerically, -h understands sizes like 2G.

Example

bash
sort -u hosts.txt
sort -t, -k3 -n inventory.csv
uniq -c intermediate Collapse repeated adjacent lines and count them.

Example

bash
# Top 5 client IPs hitting nginx
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -5
    912 10.0.0.12
    430 177.71.20.4
     88 10.0.0.31

Tip: uniq only sees neighbours, so sort first.

wc -l <file> beginner Count lines (-l), words (-w) or bytes (-c).

Example

bash
wc -l /var/log/orbit/*.log
  4182 /var/log/orbit/api.log
   311 /var/log/orbit/worker.log
  4493 total
tr <set1> <set2> intermediate Translate or delete characters in a stream.

Example

bash
echo 'orbit-api' | tr 'a-z' 'A-Z'
# Turn PATH into one entry per line
echo "$PATH" | tr ':' '\n'
ORBIT-API
xargs intermediate Turn input lines into arguments for another command.

Example

bash
# Count lines in every .conf file, even with spaces in names
find /etc/nginx -name '*.conf' -print0 | xargs -0 wc -l

Tip: Pair find -print0 with xargs -0 so file names with spaces do not break.

diff -u <old> <new> intermediate Compare two files and show the changes in unified format.

Example

bash
diff -u /etc/orbit/app.env.bak /etc/orbit/app.env
--- /etc/orbit/app.env.bak
+++ /etc/orbit/app.env
@@ -1,3 +1,3 @@
 APP_ENV=production
-WORKERS=2
+WORKERS=4
 LOG_LEVEL=info
jq '<filter>' intermediate Pretty-print, filter and reshape JSON from APIs and tools.

Example

bash
curl -s http://localhost:8080/api/health | jq .
curl -s http://localhost:8080/api/health | jq -r '.status'
{
  "status": "ok",
  "db": "up"
}
ok

Tip: Install with dnf install jq or apt install jq.

Processes & services

19 commands

See what is running, stop what misbehaves, manage background jobs and drive systemd services and their logs.

ps aux beginner List every process with its user, PID, CPU and memory use and full command.

Example

bash
ps aux | grep '[n]ginx'
root      1043  0.0  0.1  12188  2952 ?  Ss  09:12  0:00 nginx: master process /usr/sbin/nginx
nginx     1044  0.0  0.3  16740  7400 ?  S   09:12  0:01 nginx: worker process

Tip: The [n]ginx pattern stops grep from matching its own process.

ps -eo pid,user,%cpu,%mem,cmd --sort=-%mem | head intermediate Show the processes using the most memory (or CPU, with --sort=-%cpu).

Example

bash
ps -eo pid,user,%cpu,%mem,cmd --sort=-%mem | head -5
    PID USER     %CPU %MEM CMD
   2201 orbit     4.1 12.8 node /srv/orbit/current/server.js
   1310 mysql     1.2  9.4 /usr/sbin/mariadbd
pgrep -af <pattern> intermediate Find processes by name and show their PID and full command line.

Example

bash
pgrep -af node
2201 node /srv/orbit/current/server.js

Tip: Run pgrep before pkill so you see exactly what you are about to signal.

top beginner Live view of load, memory and the busiest processes. P sorts by CPU, M by memory, q quits.

Example

bash
top
# One snapshot, good for scripts
top -b -n 1 | head -15
htop beginner Interactive, colour process viewer with a tree view (F5), search (F3) and kill (F9).

Example

bash
htop

Tip: On Rocky, htop lives in EPEL: dnf install epel-release && dnf install htop.

kill -15 <pid> intermediate Send SIGTERM: ask a process to shut down cleanly.

Example

bash
kill -15 2201
kill $(pgrep -f 'node /srv/orbit')

Tip: SIGTERM is the default signal, so plain kill <pid> sends it.

kill -9 <pid> intermediate Send SIGKILL: stop a hung process immediately, with no cleanup.

Example

bash
kill -9 2201

Tip: Use it only after SIGTERM fails: the process cannot flush buffers, release locks or remove PID files.

pkill / killall <name> intermediate Signal every process that matches a name.

Example

bash
pkill -f 'node /srv/orbit'
killall -HUP nginx

Tip: -HUP asks many daemons, nginx included, to reload their config without restarting.

nice -n <n> <cmd> advanced Start a command with lower CPU priority (19 is the lowest, -20 the highest).

Example

bash
nice -n 10 tar -czf /srv/backups/orbit.tar.gz /srv/orbit
renice -n <n> -p <pid> advanced Change the priority of a process that is already running.

Example

bash
sudo renice -n 15 -p 2201
2201 (process ID) old priority 0, new priority 15
nohup <cmd> > <log> 2>&1 & intermediate Run a command in the background and keep it alive after you log out.

Example

bash
nohup python3 -m http.server 8080 > /tmp/http.log 2>&1 &
[1] 30412

Tip: For anything long-lived, a systemd service or tmux session is the sturdier choice.

jobs / bg / fg intermediate List the shell's jobs, resume a stopped job in the background, or bring one back to the front.

Example

bash
# Ctrl+Z pauses the running command
jobs
bg %1
fg %1
[1]+  Stopped                 tail -f /var/log/messages
systemctl status <service> beginner Show whether a service is running, since when, its PID and its latest log lines.

Example

bash
systemctl status nginx
● nginx.service - The nginx HTTP and reverse proxy server
     Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: disabled)
     Active: active (running) since Tue 2026-11-04 09:12:33 -03; 1h 3min ago
   Main PID: 1043 (nginx)

Tip: In scripts use systemctl is-active --quiet nginx and check the exit code.

systemctl restart / reload <service> beginner Restart a service, or reload its configuration without dropping connections.

Example

bash
sudo nginx -t && sudo systemctl reload nginx
sudo systemctl restart orbit-api

Tip: Test the config first (nginx -t, sshd -t) so a typo does not take the service down.

systemctl enable --now <service> intermediate Start a service now and make it start on every boot.

Example

bash
sudo systemctl enable --now orbit-api
Created symlink /etc/systemd/system/multi-user.target.wants/orbit-api.service → /etc/systemd/system/orbit-api.service.
systemctl --failed intermediate List units that failed to start.

Example

bash
systemctl --failed
  UNIT              LOAD   ACTIVE SUB    DESCRIPTION
● orbit-worker.service loaded failed failed Orbit queue worker
systemctl daemon-reload intermediate Make systemd re-read unit files after you create or edit one.

Example

bash
sudo vi /etc/systemd/system/orbit-api.service
sudo systemctl daemon-reload
sudo systemctl restart orbit-api
journalctl -u <service> -f intermediate Follow the logs of one systemd service.

Example

bash
journalctl -u orbit-api -f
journalctl -u nginx --since today -n 100

Tip: Add --no-pager when you pipe the output into grep.

journalctl -p err -b intermediate Show only errors (and worse) logged since the last boot.

Example

bash
journalctl -p err -b --no-pager | tail
Nov 04 09:41:07 orbit-web-01 orbit-api[2201]: db: Connection refused (127.0.0.1:5432)

System information & monitoring

12 commands

Find out what machine you are on and how it is doing: OS, kernel, uptime, memory, CPU and kernel messages.

uname -a beginner Print the kernel name, version and architecture.

Example

bash
uname -r
uname -a
5.14.0-611.el9.x86_64
Linux orbit-web-01 5.14.0-611.el9.x86_64 #1 SMP PREEMPT_DYNAMIC x86_64 GNU/Linux
cat /etc/os-release beginner Identify the distribution and its version.

Example

bash
grep PRETTY_NAME /etc/os-release
PRETTY_NAME="Ubuntu 26.04 LTS"

Tip: Scripts can source it and branch on $ID (rocky, ubuntu, debian...).

hostnamectl beginner Show or set the hostname, with the OS, kernel and virtualization type.

Example

bash
hostnamectl
sudo hostnamectl set-hostname orbit-web-01
 Static hostname: orbit-web-01
  Virtualization: kvm
Operating System: Rocky Linux 9.7 (Blue Onyx)
          Kernel: Linux 5.14.0-611.el9.x86_64
uptime beginner How long the system has been up, logged-in users and the 1, 5 and 15 minute load averages.

Example

bash
uptime
 10:16:44 up 12 days,  3:41,  2 users,  load average: 0.42, 0.37, 0.31

Tip: A load average above the number of CPU cores (nproc) means work is queuing.

free -h beginner Show used, free and available memory and swap.

Example

bash
free -h
               total        used        free      shared  buff/cache   available
Mem:           3.6Gi       1.9Gi       312Mi        42Mi       1.6Gi       1.5Gi
Swap:          2.0Gi       128Mi       1.9Gi

Tip: Read the available column: buff/cache is handed back to applications when they need it.

nproc / lscpu beginner Count CPU cores, or show the full CPU model and topology.

Example

bash
nproc
lscpu | grep -E 'Model name|^CPU\(s\)'
4
CPU(s):        4
Model name:    AMD EPYC 7J13 64-Core Processor
vmstat <delay> <count> intermediate Sample CPU, memory, swap and I/O activity at an interval.

Example

bash
vmstat 2 3
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 1  0 131072 318500  10240 1650000   0    0     3    18  210  390  4  1 94  1  0

Tip: A high wa column means processes are waiting on the disk.

lsof -i :<port> intermediate Show which process holds a network port open.

Example

bash
sudo lsof -i :8080
COMMAND  PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
node    2201 orbit   21u  IPv6  41872      0t0  TCP *:webcache (LISTEN)
lsof +L1 advanced List deleted files that a process still holds open: the reason df shows a full disk that du cannot explain.

Example

bash
sudo lsof +L1
COMMAND PID  USER FD SIZE/OFF NLINK NAME
node   2201 orbit 5w 8.1G     0 /var/log/orbit/api.log (deleted)

Tip: Restart (or signal) that process and the space comes back.

dmesg -T intermediate Read kernel messages with readable timestamps: hardware errors, OOM kills, disk problems.

Example

bash
sudo dmesg -T | tail
sudo dmesg -T | grep -i 'out of memory'
[Tue Nov  4 03:12:40 2026] Out of memory: Killed process 2201 (node) total-vm:2410332kB
timedatectl beginner Show the clock, time zone and whether NTP synchronization is active.

Example

bash
timedatectl
sudo timedatectl set-timezone America/Sao_Paulo
               Local time: Tue 2026-11-04 10:18:02 -03
                Time zone: America/Sao_Paulo (-03, -0300)
System clock synchronized: yes
              NTP service: active

Tip: A drifting clock breaks TLS, TOTP codes and log correlation between servers.

last / w intermediate See who is logged in now (w) and the recent login history (last).

Example

bash
w
last -n 5
 10:18:30 up 12 days,  3:43,  1 user,  load average: 0.40, 0.36, 0.31
USER     TTY      FROM             LOGIN@   IDLE WHAT
rocky    pts/0    177.71.20.4      10:02    0.00s w

Networking

14 commands

Check addresses and routes, test reachability, inspect open ports, resolve names and call HTTP endpoints.

ip addr show beginner Show the IP addresses and state of every network interface.

Example

bash
ip addr show enp0s6
# One line per interface
ip -br addr
lo               UNKNOWN        127.0.0.1/8 ::1/128
enp0s6           UP             10.0.0.25/24 fe80::17ff:fe02:a1b2/64
ip route show intermediate Print the routing table and the default gateway.

Example

bash
ip route show
# Which route would traffic to this IP use?
ip route get 1.1.1.1
default via 10.0.0.1 dev enp0s6 proto dhcp src 10.0.0.25 metric 100
10.0.0.0/24 dev enp0s6 proto kernel scope link src 10.0.0.25 metric 100
ifconfig -a beginner Legacy interface view from the net-tools package.

Example

bash
ifconfig -a

Tip: Many minimal installs no longer ship net-tools; ip does everything ifconfig did.

ping -c <n> <host> beginner Send a fixed number of ICMP echo requests to check reachability and latency.

Example

bash
ping -c 4 github.com
64 bytes from 140.82.113.3: icmp_seq=1 ttl=51 time=118 ms
--- github.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3004ms

Tip: Many cloud firewalls drop ICMP, so a failed ping does not always mean the host is down.

tracepath / traceroute <host> intermediate Show each hop between you and a host, to see where packets stop.

Example

bash
tracepath -n 1.1.1.1
traceroute -T -p 443 blog.example.com
dig <name> intermediate Query DNS for a record and see which server answered.

Example

bash
dig +short blog.jefersonjeronimoai.online
dig MX example.com
# Ask a specific resolver
dig @1.1.1.1 orbit.example.com
144.22.211.198

Tip: Part of bind-utils (Rocky) or dnsutils (Ubuntu). host and nslookup are the quick alternatives.

curl -I <url> beginner Fetch only the HTTP response headers.

Example

bash
curl -I https://blog.jefersonjeronimoai.online
HTTP/2 200
content-type: text/html; charset=UTF-8
server: cloudflare
cf-cache-status: HIT
curl -fsS <url> intermediate Call an endpoint quietly but still fail with an error on HTTP 4xx/5xx: the safe form for scripts.

Example

bash
curl -fsS http://localhost:8080/api/health || echo 'orbit-api is down'
# POST JSON
curl -fsS -X POST -H 'Content-Type: application/json' -d '{"job":"reindex"}' http://localhost:8080/api/jobs
{"status":"ok","db":"up"}
curl -fsSLO <url> beginner Download a file, following redirects and keeping its remote name.

Example

bash
curl -fsSLO https://github.com/cli/cli/releases/download/v2.82.0/gh_2.82.0_linux_amd64.tar.gz
wget -O <file> <url> beginner Download a URL and save it under the name you choose.

Example

bash
wget -O terraform.zip https://releases.hashicorp.com/terraform/1.17.0/terraform_1.17.0_linux_amd64.zip

Tip: wget -c resumes a download that was interrupted.

ss -tulpn intermediate List listening TCP and UDP sockets with the process that owns each one.

Example

bash
sudo ss -tulpn
sudo ss -tulpn | grep ':443'
Netid State  Local Address:Port  Process
tcp   LISTEN 0.0.0.0:22          users:(("sshd",pid=812,fd=3))
tcp   LISTEN 0.0.0.0:443         users:(("nginx",pid=1043,fd=8))

Tip: ss replaces netstat; without sudo the Process column stays empty for other users' sockets.

netstat -tulpn intermediate The older net-tools way to list listening ports and their programs.

Example

bash
sudo netstat -tulpn | grep ':80'
nc -vz <host> <port> intermediate Check whether a TCP port is reachable, without speaking its protocol.

Example

bash
nc -vz db.internal 5432
nc -vz -w 3 10.0.0.31 6379
Ncat: Connected to 10.0.0.31:5432.

Tip: If nc is missing, bash can do it: timeout 3 bash -c '</dev/tcp/db.internal/5432' && echo open.

nmap -sV <host> advanced Scan a host for open ports and identify the services and versions behind them.

Example

bash
nmap -Pn -p 22,80,443 orbit-web-01
nmap -sV 10.0.0.25
PORT    STATE SERVICE
22/tcp  open  ssh
80/tcp  open  http
443/tcp open  https

Tip: Only scan machines you own or have written permission to test.

SSH & remote transfer

11 commands

Log in to servers with keys, keep host aliases in one config file, copy files and open tunnels.

ssh <user>@<host> beginner Open an encrypted shell on a remote machine.

Example

bash
ssh rocky@144.22.211.198
# Run one command and come back
ssh rocky@144.22.211.198 'uptime'
 10:20:12 up 12 days,  3:45,  1 user,  load average: 0.35, 0.34, 0.30
ssh -i <key> <user>@<host> beginner Log in with a specific private key.

Example

bash
ssh -i ~/.ssh/orbit_ed25519 ubuntu@10.0.1.25

Tip: SSH ignores a private key that other users can read: keep it at chmod 600.

ssh-keygen -t ed25519 beginner Generate a new key pair; ed25519 is the modern default.

Example

bash
ssh-keygen -t ed25519 -C 'jeferson@laptop' -f ~/.ssh/orbit_ed25519
Your identification has been saved in /home/jeferson/.ssh/orbit_ed25519
Your public key has been saved in /home/jeferson/.ssh/orbit_ed25519.pub

Tip: Protect the key with a passphrase and let ssh-agent remember it.

ssh-copy-id <user>@<host> beginner Install your public key in the server's authorized_keys so you can log in without a password.

Example

bash
ssh-copy-id -i ~/.ssh/orbit_ed25519.pub rocky@144.22.211.198
Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'rocky@144.22.211.198'"
~/.ssh/config intermediate Give servers short aliases with their user, key and port, so ssh orbit is all you type.

Example

bash
cat >> ~/.ssh/config <<'EOF'
Host orbit
    HostName 144.22.211.198
    User rocky
    IdentityFile ~/.ssh/orbit_ed25519
EOF
ssh orbit

Tip: The alias works for scp, rsync and git too.

ssh-add <key> intermediate Load a key into ssh-agent so you type its passphrase once per session.

Example

bash
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/orbit_ed25519
ssh-add -l
256 SHA256:Qm4n... jeferson@laptop (ED25519)
scp <file> <host>:<path> intermediate Copy files to or from a server over SSH.

Example

bash
scp release.tar.gz orbit:/tmp/
# Pull a file back
scp orbit:/var/log/nginx/error.log ./
# Whole directory
scp -r dist/ orbit:/srv/orbit/releases/2026-11-04/
rsync -avz <src>/ <host>:<dest>/ intermediate Sync a directory to a server, sending only what changed.

Example

bash
rsync -avz --progress ./dist/ orbit:/srv/orbit/releases/2026-11-04/
sending incremental file list
index.html
assets/app.3f9c.js

sent 412,904 bytes  received 1,186 bytes  165,636.00 bytes/sec

Tip: The trailing slash on the source means its contents, not the folder itself.

rsync -avz --delete --dry-run advanced Mirror a directory exactly, removing remote files that no longer exist locally; preview first.

Example

bash
rsync -avz --delete --dry-run ./build/ orbit:/srv/www/current/
rsync -avz --delete ./build/ orbit:/srv/www/current/

Tip: --dry-run (-n) lists what would be deleted. Read it before the real run.

ssh -L <local>:<host>:<port> <server> advanced Forward a local port through SSH to a service that only listens inside the server.

Example

bash
# Reach the server's private MariaDB at localhost:3307
ssh -N -L 3307:127.0.0.1:3306 orbit

Tip: -N opens the tunnel without starting a remote shell; stop it with Ctrl+C.

ssh -J <jump> <target> advanced Reach a private host by hopping through a bastion server.

Example

bash
ssh -J rocky@bastion.example.com rocky@10.0.2.15

Users, groups & permissions

17 commands

Find out who you are, manage accounts and groups, and set ownership and permission bits correctly.

whoami / id beginner Show your user name, or your UID, GID and every group you belong to.

Example

bash
whoami
id orbit
rocky
uid=1001(orbit) gid=1001(orbit) groups=1001(orbit),10(wheel)
groups <user> beginner List the groups of a user.

Example

bash
groups jeferson
jeferson : jeferson wheel docker
sudo -l intermediate List what your account may run through sudo.

Example

bash
sudo -l
User rocky may run the following commands on orbit-web-01:
    (ALL) NOPASSWD: ALL
sudo -i / su - <user> intermediate Open a root login shell, or switch to another user with that user's full environment.

Example

bash
sudo -i
sudo su - postgres

Tip: The dash (or -i) loads the target user's PATH and home; without it you keep your own environment.

passwd <user> beginner Change your password, or another user's when run as root.

Example

bash
passwd
sudo passwd -l olduser

Tip: passwd -l locks an account without deleting it.

useradd -m -s /bin/bash <user> intermediate Create a user with a home directory and Bash as login shell.

Example

bash
sudo useradd -m -s /bin/bash -c 'Orbit deploy' deploy
# Service account with no login shell
sudo useradd -r -s /sbin/nologin orbit
usermod -aG <group> <user> intermediate Add a user to an extra group without removing the others.

Example

bash
sudo usermod -aG docker jeferson
# sudo access: wheel on Rocky, sudo on Ubuntu
sudo usermod -aG wheel deploy

Tip: Forget -a and -G replaces every group the user had. Changes apply on the next login.

userdel -r <user> intermediate Delete a user together with their home directory and mail spool.

Example

bash
sudo userdel -r tempuser
groupadd <group> intermediate Create a group.

Example

bash
sudo groupadd devops
sudo usermod -aG devops jeferson
chmod 755 / 644 / 600 beginner Set permissions in octal: r=4, w=2, x=1 for owner, group and others.

Example

bash
chmod 755 /usr/local/bin/backup.sh   # rwxr-xr-x scripts
chmod 644 /etc/nginx/nginx.conf      # rw-r--r-- configs
chmod 600 ~/.ssh/orbit_ed25519       # rw------- secrets

Tip: 640 (rw-r-----) fits env files the service group must read but nobody else should.

chmod u+x <file> beginner Change permissions symbolically: u, g, o or a plus or minus r, w, x.

Example

bash
chmod u+x deploy.sh
chmod go-w shared.conf
chmod -R 750 <dir> intermediate Apply permissions to a whole tree.

Example

bash
sudo chmod -R 750 /srv/orbit/bin
# Directories 755, files 644, in one pass
find /var/www/html -type d -exec chmod 755 {} + -o -type f -exec chmod 644 {} +

Tip: chmod -R on mixed trees makes every file executable; the find form treats files and folders differently.

chown -R <user>:<group> <path> intermediate Change the owner and group of a file or a whole directory.

Example

bash
sudo chown -R orbit:orbit /srv/orbit
sudo chown -R www-data:www-data /var/www/html

Tip: Set ownership and permissions together: one without the other rarely fixes access errors.

chgrp -R <group> <dir> intermediate Change only the group of files.

Example

bash
sudo chgrp -R devops /srv/shared
chmod g+s <dir> advanced Set the setgid bit on a directory so new files inherit its group: ideal for shared team folders.

Example

bash
sudo chmod 2775 /srv/shared
ls -ld /srv/shared
drwxrwsr-x. 2 root devops 6 Nov  4 10:30 /srv/shared
umask intermediate Show or set the default permissions removed from newly created files.

Example

bash
umask
umask 027
0022

Tip: 027 makes new files 640 and new directories 750.

visudo advanced Edit sudo rules safely: the file is syntax-checked before it is saved.

Example

bash
sudo visudo -f /etc/sudoers.d/deploy
# deploy ALL=(root) NOPASSWD: /usr/bin/systemctl restart orbit-api

Tip: A broken sudoers file can lock everyone out of sudo, so never edit it with a plain editor.

Disks & storage

12 commands

Find what is filling the disk, inspect block devices, mount filesystems and prepare new volumes.

df -h beginner Show size, used and free space of every mounted filesystem.

Example

bash
df -hT
Filesystem          Type  Size  Used Avail Use% Mounted on
/dev/mapper/rl-root xfs    36G   21G   15G  59% /
/dev/sda1           xfs   960M  412M  549M  43% /boot

Tip: -T adds the filesystem type column.

df -i intermediate Show inode usage: a disk can be full of tiny files while df -h still shows free space.

Example

bash
df -i /
du -sh <dir> beginner Show the total size of a directory.

Example

bash
sudo du -sh /var/log /var/lib/containers
1.2G	/var/log
7.8G	/var/lib/containers
du -sh * | sort -h intermediate Rank the entries of a directory by size to find what is eating space.

Example

bash
cd /var && sudo du -sh * 2>/dev/null | sort -h | tail -5
# Stay on one filesystem and go one level deep
sudo du -xh --max-depth=1 / | sort -h
512M	cache
1.2G	log
9.4G	lib

Tip: ncdu gives the same answer as an interactive browser.

lsblk -f beginner List disks, partitions, filesystems, UUIDs and mount points as a tree.

Example

bash
lsblk -f
NAME        FSTYPE      LABEL UUID                                 MOUNTPOINTS
sda
├─sda1      xfs               2b1c...                              /boot
└─sda2      LVM2_member       9fa0...
  └─rl-root xfs               5e77...                              /
sdb

Tip: Run it before mounting or formatting anything, so you work on the right disk.

blkid intermediate Print the UUID and type of each filesystem, the values /etc/fstab should use.

Example

bash
sudo blkid /dev/sdb1
/dev/sdb1: UUID="7c1e5a9d-3f4b-4c2a-9d10-2a6f1b8e0c44" TYPE="ext4"
findmnt intermediate Show mounts as a tree, or check one mount point and its options.

Example

bash
findmnt /data
mount | column -t | grep ' / '
TARGET SOURCE    FSTYPE OPTIONS
/data  /dev/sdb1 ext4   rw,relatime
mount <device> <dir> intermediate Attach a filesystem to a directory.

Example

bash
sudo mkdir -p /data
sudo mount /dev/sdb1 /data
umount <dir> intermediate Detach a filesystem cleanly.

Example

bash
sudo umount /data
# Busy? find who is using it
sudo fuser -vm /data

Tip: target is busy means a shell or process still has files open there, often your own cd.

/etc/fstab + mount -a advanced Make a mount permanent, then test the fstab entry without rebooting.

Example

bash
echo 'UUID=7c1e5a9d-3f4b-4c2a-9d10-2a6f1b8e0c44 /data ext4 defaults,nofail 0 2' | sudo tee -a /etc/fstab
sudo systemctl daemon-reload
sudo mount -a && findmnt /data

Tip: Use UUIDs, not /dev/sdX names, and add nofail so a missing disk does not stop the boot.

fdisk -l / parted -l advanced Show partition tables, sizes and partition types (parted handles GPT and big disks).

Example

bash
sudo fdisk -l /dev/sdb
sudo parted -l
mkfs.ext4 / mkfs.xfs <partition> advanced Create a new filesystem on a partition.

Example

bash
sudo mkfs.ext4 -L data /dev/sdb1
sudo mkfs.xfs /dev/sdc1

Tip: This wipes the partition. Confirm the device name with lsblk -f twice.

Archives & compression

7 commands

Pack directories for backups and releases, extract them anywhere and verify they arrived intact.

tar -czf <archive>.tar.gz <path> beginner Create a gzip-compressed tar archive.

Example

bash
sudo tar -czf /srv/backups/nginx-$(date +%F).tar.gz /etc/nginx

Tip: tar strips the leading / from member names, so the archive extracts relative to where you run it.

tar -xzf <archive> -C <dir> beginner Extract a tar.gz into a target directory.

Example

bash
mkdir -p /srv/orbit/releases/2026-11-04
tar -xzf release.tar.gz -C /srv/orbit/releases/2026-11-04
tar -tzf <archive> beginner List what is inside an archive without extracting it.

Example

bash
tar -tzf release.tar.gz | head
dist/
dist/index.html
dist/assets/app.3f9c.js
tar --exclude intermediate Leave folders such as node_modules or .git out of an archive.

Example

bash
tar -czf orbit-src.tar.gz --exclude=node_modules --exclude=.git orbit/
gzip -k / gunzip beginner Compress a single file (keeping the original with -k), or decompress it.

Example

bash
gzip -k access.log
gunzip access.log.gz
# Read a compressed log directly
zcat access.log.1.gz | grep ' 502 '

Tip: zgrep and zless also work on .gz files without unpacking them.

zip -r / unzip -d beginner Create a ZIP archive, or extract one into a directory.

Example

bash
zip -r configs.zip nginx/ systemd/
unzip configs.zip -d restore/
unzip -l configs.zip
sha256sum intermediate Compute or verify checksums to prove a download or backup is not corrupted.

Example

bash
sha256sum release.tar.gz > release.tar.gz.sha256
# On the server
sha256sum -c release.tar.gz.sha256
release.tar.gz: OK

Package management

9 commands

Install, update and query software on both families: dnf on Rocky/RHEL and apt on Ubuntu/Debian.

sudo apt update && sudo apt upgrade beginner Ubuntu/Debian: refresh the package lists, then install every available update.

Example

bash
sudo apt update && sudo apt upgrade -y
Hit:1 http://archive.ubuntu.com/ubuntu resolute InRelease
12 packages can be upgraded. Run 'apt list --upgradable' to see them.
sudo apt install <pkg> beginner Ubuntu/Debian: install one or more packages.

Example

bash
sudo apt install -y nginx jq htop
apt search / apt show <pkg> beginner Ubuntu/Debian: find a package, or show its version, size and description.

Example

bash
apt search postgresql-client
apt show nginx
sudo dnf upgrade beginner Rocky/RHEL: install all available updates.

Example

bash
sudo dnf check-update
sudo dnf upgrade -y
sudo dnf install <pkg> beginner Rocky/RHEL: install packages; EPEL adds many extras.

Example

bash
sudo dnf install -y epel-release
sudo dnf install -y htop jq bind-utils
dnf provides <file> intermediate Rocky/RHEL: find which package ships a command or file.

Example

bash
dnf provides '*/bin/dig'
bind-utils-32:9.16.23-31.el9.x86_64 : Utilities for querying DNS name servers
Repo        : appstream
dnf history intermediate Rocky/RHEL: review past transactions and roll one back.

Example

bash
sudo dnf history
sudo dnf history undo 42
rpm -qa / dpkg -l intermediate List every installed package (RPM-based or Debian-based).

Example

bash
rpm -qa | grep -i nginx
dpkg -l | grep -i nginx
nginx-1.20.1-22.el9.x86_64
rpm -qf / dpkg -S <file> intermediate Find which installed package owns a file.

Example

bash
rpm -qf /etc/ssh/sshd_config
dpkg -S /usr/sbin/nginx
openssh-server-8.7p1-45.el9.x86_64

Firewall & SELinux

7 commands

Open only the ports you need and keep SELinux working for you instead of switching it off.

firewall-cmd --list-all intermediate Rocky/RHEL: show the active firewalld zone with its services and ports.

Example

bash
sudo firewall-cmd --list-all
public (active)
  interfaces: enp0s6
  services: dhcpv6-client http https ssh
  ports: 8080/tcp
firewall-cmd --add-service=<svc> --permanent intermediate Rocky/RHEL: open a service or port permanently, then reload.

Example

bash
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --add-port=8080/tcp
sudo firewall-cmd --reload
success
success
success

Tip: Without --permanent the rule is lost at the next reload or reboot.

ufw allow <port> intermediate Ubuntu: allow a port or a named profile with the Uncomplicated Firewall.

Example

bash
sudo ufw allow OpenSSH
sudo ufw allow 443/tcp
sudo ufw enable
sudo ufw status verbose

Tip: Allow SSH before ufw enable, or you can lock yourself out of a remote server.

getenforce / sestatus beginner Rocky/RHEL: show whether SELinux is enforcing, permissive or disabled.

Example

bash
getenforce
sestatus | head -3
Enforcing
ausearch -m avc -ts recent advanced Rocky/RHEL: find the SELinux denials behind a permission denied error.

Example

bash
sudo ausearch -m avc -ts recent | tail -5
type=AVC msg=audit(1762260000.412:913): avc:  denied  { name_connect } for  pid=1044 comm="nginx" dest=8080 scontext=system_u:system_r:httpd_t:s0
setsebool -P <boolean> on advanced Rocky/RHEL: flip an SELinux boolean, for example to let nginx proxy to a backend port.

Example

bash
sudo setsebool -P httpd_can_network_connect on
getsebool httpd_can_network_connect
httpd_can_network_connect --> on
restorecon -Rv <path> advanced Rocky/RHEL: reset SELinux file labels after moving or copying files into place.

Example

bash
sudo restorecon -Rv /var/www/html
Relabeled /var/www/html/index.html from unconfined_u:object_r:user_home_t:s0 to unconfined_u:object_r:httpd_sys_content_t:s0

Tip: Files moved with mv keep their old label; this is a common reason nginx returns 403.

Scheduling jobs

5 commands

Run commands on a timetable with cron or systemd timers.

crontab -e / crontab -l beginner Edit or list your user's cron jobs.

Example

bash
crontab -e
crontab -l
# m h dom mon dow command
0 2 * * * /opt/scripts/backup.sh >> /var/log/backup.log 2>&1
Cron schedule fields beginner Minute, hour, day of month, month, weekday: five fields before the command.

Example

bash
# Every 5 minutes
*/5 * * * * /usr/local/bin/healthcheck.sh
# 02:30 Monday to Friday
30 2 * * 1-5 /opt/scripts/report.sh
# First day of each month at midnight
0 0 1 * * /opt/scripts/rotate.sh

Tip: cron runs with a minimal PATH and no profile, so use absolute paths and redirect output to a log.

(crontab -l; echo '<job>') | crontab - advanced Append a cron job from a script without opening an editor.

Example

bash
(crontab -l 2>/dev/null; echo '*/5 * * * * /usr/local/bin/healthcheck.sh') | crontab -
systemctl list-timers intermediate List systemd timers with their last and next run.

Example

bash
systemctl list-timers --all | head -5
NEXT                        LEFT     LAST                        PASSED  UNIT                 ACTIVATES
Tue 2026-11-04 11:00:00 -03 39min    Tue 2026-11-04 10:00:00 -03 20min   dnf-makecache.timer  dnf-makecache.service
systemd-run --on-calendar advanced Create a transient systemd timer from the command line, with logs in journalctl.

Example

bash
sudo systemd-run --on-calendar='*-*-* 03:00:00' --unit=orbit-backup /opt/scripts/backup.sh
journalctl -u orbit-backup

Tip: For permanent jobs, write a .service plus .timer pair in /etc/systemd/system instead.

Bash scripting

17 commands

The building blocks of safe shell scripts: strict mode, variables, tests, loops, functions, arrays and redirection.

#!/usr/bin/env bash beginner Shebang: the first line of a script, telling the system to run it with Bash wherever it is installed.

Example

bash
cat > hello.sh <<'EOF'
#!/usr/bin/env bash
echo "Hello from $(hostname)"
EOF
chmod +x hello.sh
./hello.sh
Hello from orbit-web-01
set -euo pipefail intermediate Strict mode: exit on any error, on unset variables and on a failure anywhere in a pipeline.

Example

bash
cat > deploy.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
release="$1"
tar -xzf "$release" -C /srv/orbit/releases/
EOF

Tip: Without it a failed step is ignored and the script keeps going on a half-finished state.

VAR="value" beginner Assign a variable: no spaces around =, and quote it every time you read it.

Example

bash
BACKUP_DIR="/srv/backups"
echo "Saving to $BACKUP_DIR"
Saving to /srv/backups

Tip: Unquoted "$VAR" splits on spaces and expands wildcards: quote by default.

$(command) beginner Command substitution: capture a command's output in a variable.

Example

bash
today=$(date +%F)
count=$(wc -l < /var/log/orbit/api.log)
echo "$today: $count lines"
2026-11-04: 4182 lines
${VAR:-default} intermediate Parameter expansion: fall back to a default, change case or cut parts of a value.

Example

bash
echo "${BRANCH:-main}"
env=production; echo "${env^^}"
file=backup.tar.gz; echo "${file%.tar.gz}"
main
PRODUCTION
backup
if [[ ... ]]; then ... fi beginner Branch on a test: -f file exists, -d directory, -z empty string, == comparison.

Example

bash
if [[ -f /srv/orbit/shared/.env ]]; then
  echo 'env found'
else
  echo 'missing .env' >&2
  exit 1
fi
$? beginner Exit status of the last command: 0 means success, anything else is a failure.

Example

bash
grep -q orbit /etc/passwd
echo $?
systemctl is-active --quiet nginx && echo up || echo down
0
up
case ... esac intermediate Choose an action from a value, such as the script's first argument.

Example

bash
case "$1" in
  start|stop|restart) sudo systemctl "$1" orbit-api ;;
  *) echo "usage: $0 {start|stop|restart}" >&2; exit 1 ;;
esac
for ... in ...; do ... done beginner Repeat commands for each item in a list or glob.

Example

bash
for host in web-01 web-02 web-03; do
  ssh "$host" uptime
done
for f in /var/log/orbit/*.log; do gzip "$f"; done
while read -r line; do ... done < file intermediate Process a file one line at a time.

Example

bash
while read -r host; do
  ping -c 1 -W 1 "$host" >/dev/null && echo "$host up" || echo "$host DOWN"
done < hosts.txt
web-01 up
web-02 DOWN

Tip: -r keeps backslashes literal; use while IFS= read -r to keep leading spaces too.

name() { ...; } intermediate Define a reusable function; its arguments arrive as $1, $2 and $@.

Example

bash
restart_on() {
  ssh "$1" 'sudo systemctl restart orbit-api'
}
restart_on web-01

Tip: Declare helper variables with local so they do not leak into the rest of the script.

arr=(a b c) / "${arr[@]}" intermediate Store a list in an array and loop over every element safely.

Example

bash
servers=(web-01 web-02 web-03)
echo "${#servers[@]} servers"
for s in "${servers[@]}"; do echo "$s"; done
3 servers
web-01
web-02
web-03
> / >> / 2> / 2>&1 beginner Redirect output: overwrite, append, send errors elsewhere, or merge errors into output.

Example

bash
npm run build > build.log 2> build.err
python3 worker.py >> worker.log 2>&1
# Discard expected noise
find / -name '*.pem' 2>/dev/null
cmd | tee <file> intermediate Show output on screen and save it to a file at the same time.

Example

bash
journalctl -u nginx --no-pager | grep -i error | tee errors.log
# Write to a root-owned file
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/90-swap.conf
cat <<'EOF' > file intermediate Here-document: write a multi-line block into a file or a command.

Example

bash
cat <<'EOF' | sudo tee /etc/orbit/app.env
APP_ENV=production
WORKERS=4
EOF

Tip: Quoting 'EOF' stops $variables inside from being expanded.

trap '<cmd>' EXIT advanced Run cleanup code however the script ends, even after an error.

Example

bash
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
curl -fsSL https://example.com/release.tar.gz -o "$tmp/r.tgz"
bash -n / shellcheck intermediate Check a script for syntax errors, or lint it for common bugs before running it.

Example

bash
bash -n deploy.sh
shellcheck deploy.sh
In deploy.sh line 5:
tar -xzf $release -C /srv/orbit/releases/
         ^------^ SC2086 (info): Double quote to prevent globbing and word splitting.

↑ ↓ navigate Enter open Esc close