DevOpsLesson
DOCKERKUBERNETESTERRAFORMAWSCI/CDLINUXGITDEVOPS ROADMAPCLOUD ROADMAPSRE ROADMAPGIT CHEATSHEETDOCKER CHEATSHEETK8S CHEATSHEETTF CHEATSHEETLINUX CHEATSHEETDOCKERFILE LINTERYAML VALIDATORCRON PARSERREGEX TESTER
DevOpsLesson

Free, comprehensive DevOps tutorials and learning roadmaps. Master Docker, Kubernetes, CI/CD, and more.

Stay Updated

Get notified about new tutorials and features.

Tutorials

  • What is DevOps?
  • Docker Tutorial
  • Terraform Tutorial
  • CI/CD Pipeline
  • All Tutorials

Roadmaps

  • DevOps Engineer
  • Cloud Engineer
  • SRE Path
  • All Roadmaps

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service

© 2026 DevOpsLesson. All rights reserved.

DOCKERKUBERNETESTERRAFORMAWSCI/CDLINUXGITDEVOPS ROADMAPCLOUD ROADMAPSRE ROADMAPGIT CHEATSHEETDOCKER CHEATSHEETK8S CHEATSHEETTF CHEATSHEETLINUX CHEATSHEETDOCKERFILE LINTERYAML VALIDATORCRON PARSERREGEX TESTER

Linux Cheatsheet

Showing 110 of 110 commands

File System & Navigation

Navigate directories, inspect paths, and analyze filesystem usage quickly

13 commands
pwdbeginner

Print the full path of your current working directory.

ls -lahbeginner

List files with permissions, owners, sizes, and hidden entries in a readable format.

cd /var/logbeginner

Change into another directory by absolute or relative path.

find . -type f -name "*.log"intermediate

Search recursively for files matching a name pattern.

find . -type f -mtime -1intermediate

Locate files modified within the last day.

locate sshd_configbeginner

Query the locate database for files by name almost instantly.

tree -L 2beginner

Display directory contents as a tree up to a chosen depth.

du -sh .beginner

Show the total size of the current directory in human-readable form.

du -sh * | sort -hintermediate

Rank files and folders by size to find what is consuming space.

df -hbeginner

Show mounted filesystem capacity, usage, and free space.

realpath ./script.shbeginner

Resolve a relative path into its canonical absolute path.

stat /etc/passwdintermediate

Inspect detailed file metadata like size, inode, mode, and timestamps.

basename /var/log/nginx/access.logbeginner

Extract the filename portion from a full path.

File Operations

Copy, move, remove, link, and permission files safely from the terminal

13 commands
cp -av src/ backup/beginner

Copy files or directories while preserving attributes and showing progress.

cp -r templates/ releases/templates/beginner

Recursively copy a directory and everything inside it.

mv old-name.txt new-name.txtbeginner

Rename a file or move it to another directory.

rm -rf build/intermediate

Force-remove files or directories recursively.

mkdir -p logs/archive/2024/07beginner

Create nested directories without failing if parents already exist.

touch deploy.logbeginner

Create an empty file or update its modification timestamp.

touch -d "2024-01-01 00:00" audit.logintermediate

Set a file timestamp manually for testing or restore workflows.

ln -s /opt/app/current /srv/www/appintermediate

Create a symbolic link that points to another file or directory.

ln existing.txt hardlink.txtadvanced

Create a hard link that references the same inode as the original file.

chmod 644 app.confbeginner

Set read-write for owner and read-only for group and others.

chmod u+x deploy.shbeginner

Add execute permission for the file owner using symbolic mode.

chmod -R 750 scripts/intermediate

Recursively apply restrictive directory and file permissions.

chown -R deploy:devops /srv/appintermediate

Change file ownership recursively to a user and group.

Text Processing

Inspect, search, transform, and compare text directly from the command line

14 commands
cat /etc/os-releasebeginner

Print a file to standard output exactly as stored.

grep -n "ERROR" app.logbeginner

Search for matching text and show the line numbers for each hit.

grep -Rin "DATABASE_URL" .intermediate

Search recursively through a project for a string or pattern.

awk -F: '{print $1, $7}' /etc/passwdadvanced

Split input into fields and print selected columns or computed values.

sed -n '1,20p' file.txtintermediate

Print only a selected range of lines from a file.

sed 's/http:/https:/g' urls.txtintermediate

Replace matching text in a stream using sed substitution syntax.

cut -d: -f1 /etc/passwdbeginner

Extract specific delimiter-separated fields from each input line.

sort -u hosts.txtbeginner

Sort lines alphabetically and remove duplicates in one step.

uniq -c access.logintermediate

Collapse adjacent duplicate lines and count their occurrences.

wc -l app.logbeginner

Count lines, words, or bytes in a file or stream.

head -n 20 server.logbeginner

Show the first lines of a file for quick inspection.

tail -f /var/log/nginx/access.logbeginner

Follow the end of a growing log file in real time.

diff -u old.conf new.confintermediate

Compare two files and show unified diff output.

less +G /var/log/syslogbeginner

Open a file in a pager for efficient scrolling, searching, and navigation.

Process Management

Monitor processes, adjust priorities, manage jobs, and inspect system services

15 commands
ps auxbeginner

List every running process with CPU, memory, user, and command details.

pgrep -af nodeintermediate

Find process IDs and commands by pattern without scanning raw ps output manually.

topbeginner

Open the built-in live process monitor for CPU and memory analysis.

htopbeginner

Use an interactive, colorized process viewer with easier sorting and filtering.

kill -15 1234intermediate

Send SIGTERM so a process can shut down gracefully.

kill -9 1234intermediate

Force-kill a stuck process using SIGKILL when graceful shutdown fails.

killall nginxintermediate

Signal all processes with the same name at once.

nice -n 10 tar -czf backup.tar.gz /srv/dataadvanced

Start a process with lower CPU scheduling priority.

nohup npm run start > app.log 2>&1 &intermediate

Run a command immune to hangups so it keeps running after logout.

jobsbeginner

List background and stopped jobs in the current shell session.

bg %1intermediate

Resume a stopped shell job and continue it in the background.

fg %1intermediate

Bring a background or stopped job back into the foreground.

systemctl status nginxbeginner

Check the current state, logs, and unit details for a systemd service.

systemctl restart nginxbeginner

Restart a service managed by systemd.

journalctl -u nginx -fintermediate

Follow logs from a specific systemd service in real time.

Networking

Inspect interfaces, test connectivity, transfer files, and troubleshoot ports

13 commands
ip addr showbeginner

Display IP addresses and status for all network interfaces.

ip route showintermediate

Inspect the kernel routing table and default gateway configuration.

ifconfig -abeginner

Show interface configuration using the legacy net-tools command set.

ping -c 4 8.8.8.8beginner

Test reachability and round-trip latency to a host.

curl -I https://example.combeginner

Fetch HTTP headers to verify status codes, redirects, and server metadata.

wget -O backup.html https://example.combeginner

Download a remote resource and save it to a chosen filename.

ss -tulpnintermediate

List listening TCP and UDP sockets with associated processes.

netstat -tulpnintermediate

Display active listening ports and bound services with the classic networking tool.

nmap -sV 192.168.1.10advanced

Scan a target host for open ports and detected service versions.

ssh devops@server.example.combeginner

Open an encrypted remote shell session over SSH.

scp app.tar.gz devops@server:/srv/releases/intermediate

Securely copy files between local and remote systems over SSH.

rsync -avz ./site/ devops@server:/var/www/site/intermediate

Synchronize files efficiently while transferring only deltas.

nc -vz localhost 5432intermediate

Test whether a TCP port is reachable using netcat.

User & Permissions

Manage accounts, groups, identity, privilege escalation, and permission models

13 commands
whoamibeginner

Print the effective username of the current shell session.

idbeginner

Show the current user ID, group ID, and supplementary groups.

sudo -lintermediate

List the commands the current user may run with sudo.

su - deployintermediate

Switch to another user account with a full login shell.

passwdbeginner

Change the password for the current account.

useradd -m -s /bin/bash aliceintermediate

Create a new user with a home directory and default Bash shell.

usermod -aG docker aliceintermediate

Append a user to an additional supplementary group.

userdel -r aliceintermediate

Delete a user account and remove its home directory.

groupadd devopsintermediate

Create a new system group for shared access control.

groups alicebeginner

List all groups that a user belongs to.

chmod 755 deploy.shbeginner

Set owner read-write-execute and read-execute for group and others using octal mode.

chmod 640 /etc/myapp.envbeginner

Restrict a sensitive file to owner read-write and group read-only using octal permissions.

chown -R alice:devops /srv/appintermediate

Recursively set both owner and group for an application directory.

Disk & Storage

Inspect block devices, mount filesystems, partition disks, and archive data

14 commands
df -hTbeginner

Show disk usage with human-readable sizes and filesystem types.

du -sh /var/logbeginner

Measure how much space a directory consumes.

lsblk -fbeginner

List block devices, partitions, filesystems, and mount points.

mount | column -tintermediate

Display all currently mounted filesystems in an easy-to-scan format.

mount /dev/sdb1 /mnt/dataintermediate

Mount a filesystem at a chosen directory so it becomes accessible.

umount /mnt/dataintermediate

Unmount a filesystem cleanly before removing or reformatting it.

fdisk -ladvanced

List disk partitions and geometry using the classic partitioning utility.

parted -ladvanced

Inspect partition tables with GNU Parted, including GPT layouts.

mkfs.ext4 /dev/sdb1advanced

Create an ext4 filesystem on a partition or block device.

tar -czf backup.tar.gz /etc/nginxbeginner

Create a compressed tar archive from files or directories.

tar -xzf backup.tar.gzbeginner

Extract a gzip-compressed tar archive into the current directory.

gzip -k app.logbeginner

Compress a file with gzip while keeping the original copy.

zip -r artifacts.zip dist/beginner

Create a ZIP archive recursively from a folder or file set.

unzip artifacts.zip -d restore/beginner

Extract a ZIP archive into a target directory.

Bash Scripting

Write safer shell scripts with variables, control flow, arrays, pipes, and cron

15 commands
#!/usr/bin/env bashbeginner

Use a portable shebang so the script runs with Bash from the current environment.

set -euo pipefailintermediate

Exit on errors, treat unset variables as failures, and catch pipe errors early.

ENVIRONMENT="production"beginner

Assign a shell variable without spaces around the equals sign.

echo "${ENVIRONMENT^^}"intermediate

Expand a variable and transform it to uppercase using Bash string operations.

if [[ -f .env ]]; then echo "found"; fibeginner

Run commands conditionally when a file, string, or status test succeeds.

case "$1" in start|stop|restart) echo "ok" ;; *) exit 1 ;; esacintermediate

Dispatch different logic branches based on an input argument.

for file in *.log; do gzip "$file"; donebeginner

Loop over matching files and run the same command for each one.

while read -r host; do ping -c 1 "$host"; done < hosts.txtintermediate

Read input line by line from standard input or a file safely.

sum() { echo "$(( $1 + $2 ))"; }intermediate

Define a reusable shell function that accepts positional parameters.

servers=("web-1" "web-2" "web-3")beginner

Create a Bash array for managing multiple related values.

echo "${servers[@]}"intermediate

Expand every array element as separate words.

command > out.log 2> err.logbeginner

Redirect standard output and standard error to different files.

command >> app.log 2>&1beginner

Append both stdout and stderr to the same log file.

journalctl -u nginx | grep ERROR | tee errors.logintermediate

Pipe output through multiple commands and save a copy with tee.

(crontab -l; echo "0 2 * * * /opt/scripts/backup.sh >> /var/log/backup.log 2>&1") | crontab -advanced

Install a recurring cron job that runs a command on a fixed schedule.

Linux Cheatsheet

A complete Linux command reference for DevOps workflows, server administration, shell productivity, and bash scripting. Search practical Linux terminal commands, copy examples instantly, and master the CLI faster.

devopslesson.com/tools/cheatsheets/linux

110 commands8 categories

File System & Navigation

13 commands
pwdbeginner

Print the full path of your current working directory.

pwd

💡 Use this before destructive commands so you know exactly where you are.

ls -lahbeginner

List files with permissions, owners, sizes, and hidden entries in a readable format.

ls -lah /etc/nginx

💡 Add --group-directories-first on supported systems to keep folders at the top.

cd /var/logbeginner

Change into another directory by absolute or relative path.

cd ~/projects/devops-lesson

💡 Use cd - to jump back to your previous directory instantly.

find . -type f -name "*.log"intermediate

Search recursively for files matching a name pattern.

find /var/log -type f -name "*.log"

💡 Combine find with -mtime, -size, or -exec for precise cleanup and audits.

find . -type f -mtime -1intermediate

Locate files modified within the last day.

find . -type f -mtime -7
locate sshd_configbeginner

Query the locate database for files by name almost instantly.

locate docker-compose.yml

💡 If results look stale, refresh the database with sudo updatedb.

tree -L 2beginner

Display directory contents as a tree up to a chosen depth.

tree -L 2 app/tools
du -sh .beginner

Show the total size of the current directory in human-readable form.

du -sh /var/lib/docker
du -sh * | sort -hintermediate

Rank files and folders by size to find what is consuming space.

du -sh /var/* | sort -h

💡 Great for identifying oversized logs, caches, and build artifacts.

df -hbeginner

Show mounted filesystem capacity, usage, and free space.

df -h

💡 Use df -i too when you suspect inode exhaustion rather than disk exhaustion.

realpath ./script.shbeginner

Resolve a relative path into its canonical absolute path.

realpath ../configs/prod.env
stat /etc/passwdintermediate

Inspect detailed file metadata like size, inode, mode, and timestamps.

stat deploy.sh
basename /var/log/nginx/access.logbeginner

Extract the filename portion from a full path.

basename /srv/releases/2024-10-01.tar.gz

💡 Use dirname for the parent path when building scripts that split file locations.

File Operations

13 commands
cp -av src/ backup/beginner

Copy files or directories while preserving attributes and showing progress.

cp -av config/ config.backup/

💡 Use -a for backups because it preserves permissions, symlinks, and timestamps.

cp -r templates/ releases/templates/beginner

Recursively copy a directory and everything inside it.

cp -r assets/ dist/assets/
mv old-name.txt new-name.txtbeginner

Rename a file or move it to another directory.

mv app.log /var/log/archive/app.log

💡 Add -n to avoid overwriting an existing destination file.

rm -rf build/intermediate

Force-remove files or directories recursively.

rm -rf .next/cache

💡 Run pwd and ls first when using rm -rf in production paths.

mkdir -p logs/archive/2024/07beginner

Create nested directories without failing if parents already exist.

mkdir -p /srv/app/releases/2024-07-14
touch deploy.logbeginner

Create an empty file or update its modification timestamp.

touch .env.local
touch -d "2024-01-01 00:00" audit.logintermediate

Set a file timestamp manually for testing or restore workflows.

touch -d "yesterday" build.marker
ln -s /opt/app/current /srv/www/appintermediate

Create a symbolic link that points to another file or directory.

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

💡 Symlinks are ideal for release switching because the target can change atomically.

ln existing.txt hardlink.txtadvanced

Create a hard link that references the same inode as the original file.

ln /var/log/app.log /var/log/app.log.link
chmod 644 app.confbeginner

Set read-write for owner and read-only for group and others.

chmod 644 /etc/nginx/nginx.conf

💡 644 is common for config files that should not be executable.

chmod u+x deploy.shbeginner

Add execute permission for the file owner using symbolic mode.

chmod u+x scripts/release.sh
chmod -R 750 scripts/intermediate

Recursively apply restrictive directory and file permissions.

chmod -R 750 /srv/app/bin
chown -R deploy:devops /srv/appintermediate

Change file ownership recursively to a user and group.

chown -R www-data:www-data /var/www/html

💡 Use chgrp -R devops shared/ when you only need to update the group.

Text Processing

14 commands
cat /etc/os-releasebeginner

Print a file to standard output exactly as stored.

cat README.md
grep -n "ERROR" app.logbeginner

Search for matching text and show the line numbers for each hit.

grep -n "Connection refused" /var/log/syslog

💡 Add -i for case-insensitive matching and -C 3 for nearby context.

grep -Rin "DATABASE_URL" .intermediate

Search recursively through a project for a string or pattern.

grep -Rin "listen 443" /etc/nginx
awk -F: '{print $1, $7}' /etc/passwdadvanced

Split input into fields and print selected columns or computed values.

awk '{print $1, $5}' access.log

💡 AWK shines when you need lightweight reporting without opening a spreadsheet.

sed -n '1,20p' file.txtintermediate

Print only a selected range of lines from a file.

sed -n '50,80p' /etc/nginx/nginx.conf
sed 's/http:/https:/g' urls.txtintermediate

Replace matching text in a stream using sed substitution syntax.

sed 's/localhost/127.0.0.1/g' .env.example

💡 Use sed -i.bak for in-place edits while keeping a backup copy.

cut -d: -f1 /etc/passwdbeginner

Extract specific delimiter-separated fields from each input line.

cut -d, -f2,4 inventory.csv
sort -u hosts.txtbeginner

Sort lines alphabetically and remove duplicates in one step.

sort -u domains.txt
uniq -c access.logintermediate

Collapse adjacent duplicate lines and count their occurrences.

sort ips.txt | uniq -c | sort -nr

💡 Remember to sort first unless duplicate lines are already adjacent.

wc -l app.logbeginner

Count lines, words, or bytes in a file or stream.

wc -l *.log
head -n 20 server.logbeginner

Show the first lines of a file for quick inspection.

head -n 5 .env.example
tail -f /var/log/nginx/access.logbeginner

Follow the end of a growing log file in real time.

tail -f app.log

💡 Use tail -n 100 -f to start with recent history before following new entries.

diff -u old.conf new.confintermediate

Compare two files and show unified diff output.

diff -u .env.example .env.production
less +G /var/log/syslogbeginner

Open a file in a pager for efficient scrolling, searching, and navigation.

less README.md

💡 Inside less, press / to search forward and n to jump to the next match.

Process Management

15 commands
ps auxbeginner

List every running process with CPU, memory, user, and command details.

ps aux | grep nginx
pgrep -af nodeintermediate

Find process IDs and commands by pattern without scanning raw ps output manually.

pgrep -af ssh

💡 Pair pgrep with pkill in real life, but use pgrep first so you know what will match.

topbeginner

Open the built-in live process monitor for CPU and memory analysis.

top
htopbeginner

Use an interactive, colorized process viewer with easier sorting and filtering.

htop

💡 htop is ideal for quickly spotting noisy processes and sending signals interactively.

kill -15 1234intermediate

Send SIGTERM so a process can shut down gracefully.

kill -15 $(pgrep -f "node server.js")
kill -9 1234intermediate

Force-kill a stuck process using SIGKILL when graceful shutdown fails.

kill -9 28491

💡 Prefer SIGTERM first because SIGKILL skips cleanup hooks and can corrupt temp state.

killall nginxintermediate

Signal all processes with the same name at once.

killall node
nice -n 10 tar -czf backup.tar.gz /srv/dataadvanced

Start a process with lower CPU scheduling priority.

nice -n 15 rsync -av /data /backup
nohup npm run start > app.log 2>&1 &intermediate

Run a command immune to hangups so it keeps running after logout.

nohup python3 -m http.server 8080 > server.log 2>&1 &
jobsbeginner

List background and stopped jobs in the current shell session.

jobs
bg %1intermediate

Resume a stopped shell job and continue it in the background.

bg %2
fg %1intermediate

Bring a background or stopped job back into the foreground.

fg %1
systemctl status nginxbeginner

Check the current state, logs, and unit details for a systemd service.

systemctl status docker

💡 Use systemctl is-active service-name in scripts when you only need a health check.

systemctl restart nginxbeginner

Restart a service managed by systemd.

sudo systemctl restart sshd
journalctl -u nginx -fintermediate

Follow logs from a specific systemd service in real time.

journalctl -u docker --since today

💡 Add -n 100 to review recent lines before following live output.

Networking

13 commands
ip addr showbeginner

Display IP addresses and status for all network interfaces.

ip addr show eth0

💡 Use ip -br addr for a concise summary on modern Linux distributions.

ip route showintermediate

Inspect the kernel routing table and default gateway configuration.

ip route show
ifconfig -abeginner

Show interface configuration using the legacy net-tools command set.

ifconfig -a

💡 Prefer ip addr on newer systems because ifconfig is deprecated on many distros.

ping -c 4 8.8.8.8beginner

Test reachability and round-trip latency to a host.

ping -c 4 github.com
curl -I https://example.combeginner

Fetch HTTP headers to verify status codes, redirects, and server metadata.

curl -I https://api.github.com

💡 Use curl -sS for scripts so errors remain visible without a progress meter.

wget -O backup.html https://example.combeginner

Download a remote resource and save it to a chosen filename.

wget https://releases.hashicorp.com/terraform.zip
ss -tulpnintermediate

List listening TCP and UDP sockets with associated processes.

ss -tulpn | grep :443

💡 ss is the modern replacement for many netstat use cases.

netstat -tulpnintermediate

Display active listening ports and bound services with the classic networking tool.

netstat -tulpn | grep :80
nmap -sV 192.168.1.10advanced

Scan a target host for open ports and detected service versions.

nmap -Pn -p 22,80,443 server.internal

💡 Use nmap only on systems you are authorized to assess.

ssh devops@server.example.combeginner

Open an encrypted remote shell session over SSH.

ssh -i ~/.ssh/prod.pem ubuntu@10.0.1.25
scp app.tar.gz devops@server:/srv/releases/intermediate

Securely copy files between local and remote systems over SSH.

scp -r dist/ ubuntu@10.0.1.25:/var/www/app/
rsync -avz ./site/ devops@server:/var/www/site/intermediate

Synchronize files efficiently while transferring only deltas.

rsync -avz --delete ./build/ deploy@web-01:/srv/www/current/

💡 rsync is safer and faster than repeated full scp uploads for deployments.

nc -vz localhost 5432intermediate

Test whether a TCP port is reachable using netcat.

nc -vz db.internal 3306

💡 Netcat is perfect for quick smoke tests when curl or ssh are too specific.

User & Permissions

13 commands
whoamibeginner

Print the effective username of the current shell session.

whoami
idbeginner

Show the current user ID, group ID, and supplementary groups.

id deploy
sudo -lintermediate

List the commands the current user may run with sudo.

sudo -l

💡 Useful when diagnosing why a deployment user cannot run a privileged action.

su - deployintermediate

Switch to another user account with a full login shell.

su - postgres
passwdbeginner

Change the password for the current account.

passwd alice
useradd -m -s /bin/bash aliceintermediate

Create a new user with a home directory and default Bash shell.

sudo useradd -m -s /bin/bash deploy
usermod -aG docker aliceintermediate

Append a user to an additional supplementary group.

sudo usermod -aG sudo alice

💡 Always include -a with -G so you do not overwrite existing group memberships.

userdel -r aliceintermediate

Delete a user account and remove its home directory.

sudo userdel -r tempuser
groupadd devopsintermediate

Create a new system group for shared access control.

sudo groupadd developers
groups alicebeginner

List all groups that a user belongs to.

groups deploy
chmod 755 deploy.shbeginner

Set owner read-write-execute and read-execute for group and others using octal mode.

chmod 755 /usr/local/bin/backup.sh

💡 755 is common for scripts that should be executable but not writable by everyone.

chmod 640 /etc/myapp.envbeginner

Restrict a sensitive file to owner read-write and group read-only using octal permissions.

chmod 640 /srv/app/.env
chown -R alice:devops /srv/appintermediate

Recursively set both owner and group for an application directory.

chown -R www-data:www-data /var/www/app

💡 Pair chown with chmod to fully correct both ownership and access mode issues.

Disk & Storage

14 commands
df -hTbeginner

Show disk usage with human-readable sizes and filesystem types.

df -hT
du -sh /var/logbeginner

Measure how much space a directory consumes.

du -sh /var/lib/docker
lsblk -fbeginner

List block devices, partitions, filesystems, and mount points.

lsblk -f

💡 Run lsblk before mounting a new disk so you target the correct device.

mount | column -tintermediate

Display all currently mounted filesystems in an easy-to-scan format.

mount | column -t
mount /dev/sdb1 /mnt/dataintermediate

Mount a filesystem at a chosen directory so it becomes accessible.

sudo mount /dev/nvme1n1p1 /data
umount /mnt/dataintermediate

Unmount a filesystem cleanly before removing or reformatting it.

sudo umount /data

💡 Use lsof or fuser first if umount reports that the device is busy.

fdisk -ladvanced

List disk partitions and geometry using the classic partitioning utility.

sudo fdisk -l /dev/sdb
parted -ladvanced

Inspect partition tables with GNU Parted, including GPT layouts.

sudo parted -l
mkfs.ext4 /dev/sdb1advanced

Create an ext4 filesystem on a partition or block device.

sudo mkfs.ext4 /dev/nvme1n1p1

💡 Formatting destroys data, so verify the device name carefully with lsblk first.

tar -czf backup.tar.gz /etc/nginxbeginner

Create a compressed tar archive from files or directories.

tar -czf release.tar.gz dist/
tar -xzf backup.tar.gzbeginner

Extract a gzip-compressed tar archive into the current directory.

tar -xzf release.tar.gz -C /srv/releases/
gzip -k app.logbeginner

Compress a file with gzip while keeping the original copy.

gzip -k access.log
zip -r artifacts.zip dist/beginner

Create a ZIP archive recursively from a folder or file set.

zip -r configs.zip nginx/ systemd/
unzip artifacts.zip -d restore/beginner

Extract a ZIP archive into a target directory.

unzip backup.zip -d restore/

Bash Scripting

15 commands
#!/usr/bin/env bashbeginner

Use a portable shebang so the script runs with Bash from the current environment.

#!/usr/bin/env bash

💡 Place the shebang on the first line of every executable Bash script.

set -euo pipefailintermediate

Exit on errors, treat unset variables as failures, and catch pipe errors early.

set -euo pipefail

💡 This is one of the best defaults for safer production shell scripts.

ENVIRONMENT="production"beginner

Assign a shell variable without spaces around the equals sign.

BACKUP_DIR="/srv/backups"
echo "${ENVIRONMENT^^}"intermediate

Expand a variable and transform it to uppercase using Bash string operations.

echo "${branch:-main}"

💡 Parameter expansion like ${var:-default} is cleaner than many small if statements.

if [[ -f .env ]]; then echo "found"; fibeginner

Run commands conditionally when a file, string, or status test succeeds.

if [[ -d logs ]]; then rm -rf logs; fi
case "$1" in start|stop|restart) echo "ok" ;; *) exit 1 ;; esacintermediate

Dispatch different logic branches based on an input argument.

case "$ENV" in prod) URL=prod ;; dev) URL=dev ;; esac
for file in *.log; do gzip "$file"; donebeginner

Loop over matching files and run the same command for each one.

for host in web-1 web-2 web-3; do ssh "$host" uptime; done
while read -r host; do ping -c 1 "$host"; done < hosts.txtintermediate

Read input line by line from standard input or a file safely.

while read -r line; do echo "$line"; done < .env

💡 Use -r with read so backslashes are not interpreted unexpectedly.

sum() { echo "$(( $1 + $2 ))"; }intermediate

Define a reusable shell function that accepts positional parameters.

deploy() { ssh "$1" "sudo systemctl restart app"; }
servers=("web-1" "web-2" "web-3")beginner

Create a Bash array for managing multiple related values.

files=(Dockerfile docker-compose.yml .env)
echo "${servers[@]}"intermediate

Expand every array element as separate words.

for server in "${servers[@]}"; do echo "$server"; done
command > out.log 2> err.logbeginner

Redirect standard output and standard error to different files.

npm run build > build.log 2> build.err

💡 Use 2>/dev/null only when you deliberately want to hide expected noise.

command >> app.log 2>&1beginner

Append both stdout and stderr to the same log file.

python3 worker.py >> worker.log 2>&1
journalctl -u nginx | grep ERROR | tee errors.logintermediate

Pipe output through multiple commands and save a copy with tee.

cat access.log | awk '{print $1}' | sort | uniq -c

💡 Pipes let each tool do one job well, which is the Unix philosophy in practice.

(crontab -l; echo "0 2 * * * /opt/scripts/backup.sh >> /var/log/backup.log 2>&1") | crontab -advanced

Install a recurring cron job that runs a command on a fixed schedule.

(crontab -l; echo "*/5 * * * * /usr/local/bin/healthcheck.sh") | crontab -

💡 Cron uses a minimal environment, so prefer absolute paths for commands and files.

devopslesson.comFree DevOps Cheatsheets · Tutorials · Roadmaps