Skip to content

Cheat sheet: Linux & shell

Linux basics (cd, ls -lh, cp, mkdir, rm, cat, man, sudo, apt, ssh) to pipelines, every flag and pipe explained.

Index
  • #cheatsheet
  • #linux
  • #shell
Updated

Also:bash · shell · basics · cd · ls · ls -lh · pwd · mkdir · cp · mv · rm · cat · less · chmod · sudo · apt · ssh · pipes · grep · awk · sed · find · xargs · redirect · 2>&1

Each entry shows the command, a copy button, and what every part does: sub-command, flag, pipe, redirect and placeholder, in the order they appear. <placeholders> are the bits you replace.

251 items
Click a command to see what each part does.

Navigate & list13

  • cd <dir>Go into a folder

    What each part does

    1. cdchange directory (a shell built-in)
    2. <dir>relative path (logs) or absolute path (/var/log)
  • cd ~Go to your home folder

    What each part does

    1. cdchange directory
    2. ~your home directory (/home/<user>); plain "cd" with no argument does the same
  • cd ..; cd -Go up one level / back to the previous folder

    What each part does

    1. cd ..".." is the parent of the current folder
    2. ;then
    3. cd -jump back to the folder you were in before (and print it)
  • pwdShow where you are

    What each part does

    1. pwdprint working directory: the full path of the current folder
  • lsList files

    What each part does

    1. lslist the current folder (names only, hidden dot-files not shown)
  • ls -lLong listing: permissions, owner, size, date

    What each part does

    1. lslist directory contents
    2. -llong format: permissions, links, owner, group, size in bytes, modified date, name
  • ls -laInclude hidden files (.env, .git …)

    What each part does

    1. -llong format
    2. -a--all: also show entries starting with "." (including . and ..)

    Tip ls -lA shows hidden files but leaves out . and ..

  • ls -lhLong listing with readable sizes

    What each part does

    1. -llong format
    2. -h--human-readable: sizes like 4.0K, 12M, 1.3G instead of bytes (works with -l)
  • ls -ltrNewest files last (great for log folders)

    What each part does

    1. -llong format
    2. -tsort by modification time, newest first
    3. -r--reverse: flip the order, so the newest ends up at the bottom next to your prompt
  • ls -lhSBiggest files first

    What each part does

    1. -l -hlong format with readable sizes
    2. -Ssort by size, largest first
  • ls -d */List only sub-folders

    What each part does

    1. -d--directory: list the folders themselves, not what is inside them
    2. */shell glob that matches only directories
  • ls -R <dir>List everything below, recursively

    What each part does

    1. -R--recursive: list every sub-folder too
  • tree -L 2 <dir>Folder tree, two levels deep

    What each part does

    1. treedraw the folder structure (install it: apt install tree)
    2. -L 2limit depth to 2 levels

Create, copy, move, delete13

  • mkdir -p <path/to/dir>Create a folder (and parents) in one go

    What each part does

    1. mkdirmake directory
    2. -pcreate missing parent folders too; no error if it already exists
  • touch <file>Create an empty file / update its timestamp

    What each part does

    1. touchcreate the file if missing; if it exists, set its modified time to now
  • cp <src> <dest>Copy a file

    What each part does

    1. cpcopy
    2. <src>file to copy
    3. <dest>new file name, or a folder to copy into
  • cp -r <src-dir> <dest-dir>Copy a folder with everything in it

    What each part does

    1. -r--recursive: copy directories and their contents
  • cp -a <src> <dest>Copy keeping permissions, owner and times (backups)

    What each part does

    1. -a--archive: recursive + keep symlinks, permissions, ownership and timestamps
  • cp -i <src> <dest>Copy but ask before overwriting

    What each part does

    1. -i--interactive: prompt before overwriting an existing file
  • mv <old-name> <new-name>Rename a file or folder

    What each part does

    1. mvmove: within the same folder this is a rename
  • mv <file1> <file2> <dir>/Move files into a folder

    What each part does

    1. <file1> <file2>one or more sources
    2. <dir>/destination folder (the trailing / makes it clear it is a folder)

    Tip Add -i to be asked before overwriting, -n to never overwrite.

  • rm <file>Delete a fileCaution

    What each part does

    1. rmremove (no recycle bin: it is gone)
  • rm -i <files>Delete, but confirm each fileCaution

    What each part does

    1. -iprompt before every removal
  • rm -rf <dir>Delete a folder and everything in itDestructive

    What each part does

    1. -r--recursive: remove directories and their contents
    2. -f--force: never prompt, ignore files that don't exist
    3. <dir>double-check this path: there is no undo

    Tip Run ls <dir> first. Never run it with a variable that might be empty (rm -rf "$DIR/").

  • rmdir <dir>Delete an empty folder

    What each part does

    1. rmdirremove a directory only if it is empty (safe)
  • ln -s <target> <link-name>Create a symbolic link (shortcut)

    What each part does

    1. lnmake links
    2. -s--symbolic: a symlink pointing to <target> (without -s it makes a hard link)
    3. <target>the real file or folder
    4. <link-name>the shortcut to create

View & compare files9

  • cat <file>Print a file

    What each part does

    1. catconcatenate: print one or more files to the screen
  • cat -n <file>Print with line numbers

    What each part does

    1. -n--number: number every output line
  • less <file>Read a long file page by page

    What each part does

    1. lessscroll a file: Space/b = page down/up, /text = search, n = next match, G = end, q = quit
  • head -n 20 <file>First lines of a file

    What each part does

    1. headstart of a file
    2. -n 20how many lines (default 10)
  • tail -n 50 <file>Last lines of a file

    What each part does

    1. tailend of a file
    2. -n 50how many lines (default 10); add -f to keep following
  • wc -l <file>Count lines, words, bytes

    What each part does

    1. wcword count
    2. -lcount lines only (-w words, -c bytes)
  • diff -u <old-file> <new-file>Compare two files

    What each part does

    1. diffshow differences (exit 0 = same, 1 = different)
    2. -uunified format: - removed lines, + added lines, 3 lines of context
  • file <file>What kind of file is this?

    What each part does

    1. filedetect the type: text, ELF binary, gzip, JSON…
  • stat <file>Size, permissions and timestamps of a file

    What each part does

    1. statdetailed metadata: size, inode, permissions, access/modify/change times

Permissions & ownership (chmod, chown, umask, ACL)31

  • ls -l <file>Read a permission string

    What it means

    On a directory: r = list names, w = create/delete entries, x = enter it / reach things inside.

    What each part does

    1. -rwxr-xr-xexample output; 1st char is the type: - file, d directory, l symlink
    2. rwxchars 2-4, owner (user): r read, w write, x execute
    3. r-xchars 5-7, group: - means "not allowed"
    4. r-xchars 8-10, others (everyone else)
    5. s / ts in an x slot = setuid/setgid, t in the last slot = sticky (capital S/T = bit set but no x)
    6. +a trailing + means extra ACL entries exist (see getfacl)
  • stat -c '%a %A %U:%G %n' <file>See permissions as numbers

    What each part does

    1. stat -cprint chosen fields
    2. %apermissions in octal, e.g. 755
    3. %Athe same as letters, e.g. -rwxr-xr-x
    4. %U:%Gowner user and group
    5. %nfile name
  • chmod 755 <file-or-dir>Octal modes explained: 755

    What each part does

    1. chmodchange mode (permissions)
    2. 7owner = 4 read + 2 write + 1 execute = rwx
    3. 5group = 4 read + 1 execute = r-x
    4. 5others = r-x

    Tip Typical for folders, scripts and binaries.

  • chmod 644 <file>Regular files: owner writes, everyone reads

    What each part does

    1. 6owner rw- (4+2)
    2. 4group r--
    3. 4others r--

    Tip Typical for config files, web content, documents.

  • chmod 600 <file>Private file: only the owner

    What each part does

    1. 6owner rw-
    2. 0group: nothing
    3. 0others: nothing

    Tip Use for secrets: .env files, private keys, kubeconfig, credentials.

  • chmod 700 <dir>Private folder / script: only the owner

    What each part does

    1. 7owner rwx
    2. 0 0group and others: no access at all
  • chmod 750 <dir>; chmod 640 <file>Shared with the group, hidden from others

    What each part does

    1. 750dir: owner rwx, group r-x (can enter and read), others none
    2. 640file: owner rw-, group r--, others none
  • chmod 400 <file>Read-only for the owner

    What each part does

    1. 4owner r-- only
    2. 00nobody else

    Tip AWS .pem key files are expected to be 400 or 600.

  • chmod 777 <path>777: everyone can do everything (avoid)Destructive

    What each part does

    1. 7 7 7rwx for owner, group and ALL other users

    Tip Any user or compromised process can change or replace the file, or delete files in the folder. Fix ownership or group instead (chown / chgrp + 775 or 770).

  • chmod +x <script>.sh && ./<script>.shMake a script executable and run it

    What each part does

    1. +xadd execute (no who-letter = for all, minus the umask bits)
    2. &&then
    3. ./<script>.shrun it from the current folder (. is not on PATH)
  • chmod u+x,g-w,o-rwx <file>Symbolic: add or remove for owner/group/others

    What each part does

    1. u+xu = owner (user): add execute
    2. ,separate clauses
    3. g-wg = group: remove write
    4. o-rwxo = others: remove everything

    Tip Who: u, g, o, a (all). Operator: + add, - remove, = set exactly. Perms: r w x X s t.

  • chmod u=rwx,go=rx <path>Symbolic: set exact permissions

    What each part does

    1. u=rwxowner gets exactly rwx
    2. go=rxgroup and others get exactly r-x (same as 755)
  • chmod a+r <file>Give everyone read access

    What each part does

    1. a+ra = all (owner, group, others): add read
  • chmod -R u+rwX,go+rX,go-w <dir>Recursive, the safe way (capital X)

    What each part does

    1. -R--recursive: the folder and everything inside
    2. u+rwXowner: read, write, and execute only for folders / files already executable
    3. go+rXgroup/others: read, and enter folders
    4. go-wgroup/others: no write

    Tip X (capital) avoids making every plain file executable, which chmod -R 755 would do.

  • find <dir> -type d -exec chmod 755 {} + && find <dir> -type f -exec chmod 644 {} +Folders 755, files 644 (fix a messy tree)Caution

    What each part does

    1. find <dir> -type devery directory under <dir>
    2. -exec chmod 755 {} +run chmod on them in batches ({} = the found names)
    3. &&then
    4. -type f … chmod 644every regular file gets 644

    Tip Re-add +x afterwards to scripts that need it.

  • chmod --reference=<source-file> <file>Copy permissions from another file

    What each part does

    1. --reference=<source-file>use that file's mode instead of typing one
  • sudo chown <user> <path>Change the owner

    What each part does

    1. chown <user>new owner; the group stays the same
  • sudo chown -R <user>:<group> <path>Change owner and group, recursively

    What each part does

    1. -Rrecursive
    2. <user>:<group>both at once (no spaces). <user>: alone = also set the user's login group
  • sudo chgrp -R <group> <path>Change only the group

    What each part does

    1. chgrpchange group (same as chown :<group>)
    2. -Rrecursive
  • sudo chown -R --from=<old-user> <new-user> <dir>Re-own only files that belong to someone else

    What each part does

    1. --from=<old-user>change only files currently owned by <old-user>
    2. <new-user>new owner
  • sudo chgrp <group> <dir> && sudo chmod 2775 <dir>Shared team folder: new files keep the folder group

    What each part does

    1. chgrp <group> <dir>folder belongs to the team group
    2. 2setgid bit: new files/folders inside inherit the folder's group
    3. 775owner and group rwx, others r-x

    Tip Symbolic form: chmod g+s <dir>.

  • sudo chmod 1777 <dir>Sticky folder: users can only delete their own files

    What each part does

    1. 1sticky bit: only the file owner (or dir owner/root) can delete or rename entries
    2. 777everyone can create files

    Tip This is how /tmp is set up (drwxrwxrwt). Symbolic: chmod +t <dir>.

  • sudo find / -xdev -type f -perm /4000 2>/dev/nullFind setuid programs (security audit)

    What each part does

    1. -xdevstay on one filesystem
    2. -type ffiles only
    3. -perm /4000any file with the setuid bit (runs as its owner, often root)
    4. 2>/dev/nullhide "Permission denied" noise
  • find <dir> -type f -perm -o+wFind world-writable files

    What each part does

    1. -perm -o+w"-" = all listed bits must be set: others have write
  • umask; umask 027Default permissions for new files (umask)

    What each part does

    1. umaskshow the current mask (usually 0022)
    2. umask 027set it for this shell: bits in the mask are REMOVED from new files

    Tip New files start from 666, folders from 777. 022 → files 644, dirs 755. 027 → 640 / 750. 077 → 600 / 700. Put it in ~/.bashrc or the service unit (UMask=) to keep it.

  • setfacl -m u:<user>:rwx <path>Give one extra user access (ACL)

    What each part does

    1. setfaclset file access control lists
    2. -m--modify: add or change an entry
    3. u:<user>:rwxentry: u = user, then the name, then permissions (g:<group>:rx for a group)
  • setfacl -R -m u:<user>:rwX <dir> && setfacl -d -m u:<user>:rwX <dir>ACL for everything inside, and for future files

    What each part does

    1. -Rapply to existing files recursively
    2. -d--default: entries that NEW files and folders inside will inherit
    3. rwXX = execute only on folders/executables
  • getfacl <path>Show ACLs

    What each part does

    1. getfaclowner, group, and every ACL entry with its effective rights (mask applies)
  • setfacl -x u:<user> <path>; setfacl -b <path>Remove ACL entries

    What each part does

    1. -x u:<user>remove that user's entry (no permissions in the spec)
    2. -b--remove-all: drop every extra entry, keep owner/group/others
  • chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys ~/.ssh/id_ed25519SSH files: fix permissions so sshd accepts them

    What each part does

    1. 700 ~/.sshonly you can enter or list the folder
    2. 600 authorized_keysonly you can read/write the list of allowed keys
    3. 600 id_ed25519private key readable only by you (public .pub can be 644)

    Tip With StrictModes (default yes) sshd refuses keys if these are group/world-writable.

  • namei -l <path>Why is access denied? Check every folder on the path

    What each part does

    1. namei -llist owner, group and mode of each component: missing x on any parent blocks access

Help & shell basics11

  • man <command>Read the manual for a command

    What each part does

    1. manmanual page; / to search, q to quit
    2. <command>e.g. man ls, man tar
  • <command> --helpQuick help for a command

    What each part does

    1. --helpmost tools print their options and exit
  • which <command>; type <command>Where is a command installed?

    What each part does

    1. whichpath of the program that would run
    2. typealso tells you if it is an alias, built-in or function
  • history | grep <word>Search your command history

    What each part does

    1. historynumbered list of commands you ran
    2. | grep <word>only the ones containing <word>; re-run one with !<number>

    Tip Faster: press Ctrl+R and start typing to search history interactively.

  • sudo !!Re-run the last command with sudo

    What each part does

    1. sudorun as root
    2. !!history expansion: the whole previous command
  • alias ll='ls -lh'Create a shortcut command

    What each part does

    1. aliasdefine a short name for a command
    2. ll='ls -lh'typing ll now runs ls -lh (add it to ~/.bashrc to keep it)
  • echo "$HOME"Print a variable

    What each part does

    1. echoprint text
    2. "$HOME"value of the HOME variable; quotes keep spaces intact
  • export <NAME>=<value>Set a variable for this shell and its programs

    What each part does

    1. exportmake the variable visible to programs you start from this shell
    2. <NAME>=<value>no spaces around =
  • env | grep <NAME>Show environment variables

    What each part does

    1. envall environment variables
    2. | grep <NAME>only matching ones
  • sudo <command>; sudo -iRun as root / open a root shellCaution

    What each part does

    1. sudo <command>run one command as root (asks for your password)
    2. sudo -iinteractive root login shell; type exit to leave
  • Tab · Ctrl+C · Ctrl+R · Ctrl+L · Ctrl+DUseful keys

    What each part does

    1. Tabcomplete file and command names (press twice to list options)
    2. Ctrl+Cstop the running command
    3. Ctrl+Rsearch command history
    4. Ctrl+Lclear the screen (same as clear)
    5. Ctrl+Dend input / log out of the shell

Users & groups6

  • whoami; idWho am I?

    What each part does

    1. whoamiyour user name
    2. idyour user ID, primary group and all groups
  • groups <user>Which groups is a user in?

    What each part does

    1. groupslist group memberships (yours if no user given)
  • su - <user>Switch to another user

    What each part does

    1. susubstitute user
    2. -start a full login shell (their home folder and environment)
  • sudo useradd -m -s /bin/bash <user>Create a user with a home folder and bash

    What each part does

    1. useraddcreate a user account
    2. -m--create-home: create /home/<user> with the skeleton files
    3. -s /bin/bash--shell: login shell
  • sudo usermod -aG <group> <user>Add a user to a group (keep other groups)

    What each part does

    1. usermodmodify a user
    2. -a--append: add to the group (only valid with -G)
    3. -G <group>supplementary group(s). Without -a the user is REMOVED from groups not listed

    Tip Typical: sudo usermod -aG docker $USER, then log out and in again.

  • sudo passwd <user>Set or change a password

    What each part does

    1. passwdchange the password (your own if no user given, no sudo needed)

Install packages7

  • sudo apt update && sudo apt upgrade -yRefresh package lists and upgrade (Debian/Ubuntu)

    What each part does

    1. apt updatedownload the latest package lists (installs nothing)
    2. &&only if that worked
    3. apt upgradeinstall newer versions of installed packages
    4. -yanswer yes to the prompt
  • sudo apt install -y <package>Install a package

    What each part does

    1. apt installinstall a package and its dependencies
    2. -yno confirmation prompt
  • sudo apt remove <package>Remove a packageCaution

    What each part does

    1. apt removeuninstall (keeps config files; apt purge removes those too)
  • apt search <word>Find a package

    What each part does

    1. apt searchsearch package names and descriptions
  • apt list --installed | grep <package>Is it installed?

    What each part does

    1. apt list --installedevery installed package
    2. | grep <package>filter to the one you want
  • sudo dnf install -y <package>Install on RHEL / Fedora / Amazon Linux

    What each part does

    1. dnf installinstall with the dnf package manager (yum on older systems)
    2. -yno prompt
  • apk add --no-cache <package>Install on Alpine (common in containers)

    What each part does

    1. apk addAlpine's package manager
    2. --no-cachedon't keep the package index: smaller images

Package & software versions (any distro)29

  • hostnamectlOS, version and kernel in one view

    What each part does

    1. hostnamectlhostname, operating system and version, kernel, architecture, virtualization (systemd systems)
  • <program> --versionVersion of any program

    What each part does

    1. <program> --versionmost tools print their version; some use -v or -V (nginx -v, java -version, python3 -V)
  • dpkg -S "$(command -v <program>)"Where is a command, and which package installed it? (Debian / Ubuntu)

    What each part does

    1. command -v <program>full path of the program the shell would run
    2. dpkg -S <path>the package that owns that file
  • rpm -qf "$(command -v <program>)"Which package installed a command? (RHEL / Fedora / Amazon Linux)

    What each part does

    1. command -v <program>full path of the program
    2. rpm -qf <path>package (name-version-release) that owns that file
  • dpkg-query -W -f='${Package} ${Version} ${Status}\n' <package>Installed version of one package (Debian / Ubuntu)

    What each part does

    1. dpkg-query -Wshow installed package info
    2. -f='${Package} ${Version} ${Status}\n'output format: name, version, install status
    3. <package>package name; wildcards work, e.g. 'openssl*'
  • apt-cache policy <package>Installed vs available version (Debian / Ubuntu)

    What each part does

    1. apt-cache policyInstalled: version now, Candidate: what apt install/upgrade would get, plus the version table per repo
    2. <package>package name
  • apt list -a <package>All versions the repos offer (Debian / Ubuntu)

    What each part does

    1. apt list -aevery available version, marked [installed] / [upgradable]
  • sudo apt update && apt list --upgradablePackages with updates available (Debian / Ubuntu)

    What each part does

    1. apt updaterefresh package lists first, or the answer is stale
    2. apt list --upgradableinstalled packages with a newer version: name, new version, [upgradable from: old]
  • dpkg-query -W -f='${Package}\t${Version}\n' | sortEvery installed package with its version (Debian / Ubuntu)

    What each part does

    1. dpkg-query -W -f='...'name TAB version for every installed package
    2. | sortalphabetical; redirect to a file to diff two servers
  • rpm -q <package>Installed version of one package (RHEL / Fedora / Amazon Linux / SUSE)

    What each part does

    1. rpm -q <package>name-version-release.arch, or 'package ... is not installed'
  • rpm -qi <package>Details of an installed package (RHEL family)

    What each part does

    1. rpm -qiversion, release, install date, vendor, build date, summary
  • dnf list --showduplicates <package>Installed and available versions (RHEL / Fedora)

    What each part does

    1. dnf listInstalled Packages section and Available Packages section
    2. --showduplicatesevery available version, not just the newest (to pick one to install or downgrade)
  • dnf check-updatePackages with updates available (RHEL / Fedora)

    What each part does

    1. dnf check-updatelist pending updates; exit code 100 means updates exist, 0 means none (yum check-update on older systems)
  • dnf updateinfo list --securityPending security updates only (RHEL / Fedora)

    What each part does

    1. dnf updateinfo listadvisories for available updates
    2. --securityonly security fixes, with severity and advisory ID
  • rpm -qa --last | head -30Every installed package, newest installs first (RHEL family)

    What each part does

    1. rpm -qaall installed packages
    2. --lastsorted by install/update time, newest first, with the date
    3. | head -30the 30 most recent
  • dnf history; dnf history info <id>What changed recently? (RHEL / Fedora)

    What each part does

    1. dnf historyevery install/upgrade/remove transaction with date and user
    2. dnf history info <id>exact packages and versions in that transaction; dnf history undo <id> reverts it
  • grep -E ' (install|upgrade) ' /var/log/dpkg.logWhat was installed or upgraded recently? (Debian / Ubuntu)

    What each part does

    1. grep -E ' (install|upgrade) 'only install and upgrade lines (date, package, old and new version)
    2. /var/log/dpkg.logdpkg's log; older months are in dpkg.log.1 and .gz files (zgrep)
  • apk info -v <package>; apk policy <package>Installed version of one package (Alpine)

    What each part does

    1. apk info -v <package>installed name-version
    2. apk policy <package>installed and available versions per repository
  • apk update && apk version -l '<'Packages with updates available (Alpine)

    What each part does

    1. apk updaterefresh the index
    2. apk version -l '<'only packages whose installed version is older than the repo's
  • zypper info <package>Installed version of one package (SUSE)

    What each part does

    1. zypper infoversion, repository, installed status of a package
  • snap list; flatpak list --columns=application,versionSnap and Flatpak packages with versions

    What each part does

    1. snap listsnaps: name, version, revision, channel
    2. flatpak list --columns=...flatpak apps and their versions
  • python3 -m pip list; python3 -m pip show <package>Python packages and versions

    What each part does

    1. python3 -m pip listevery package in this Python environment with its version (add --outdated for updates)
    2. pip show <package>version, location and dependencies of one package
  • node --version; npm ls -g --depth=0Global Node.js packages and versions

    What each part does

    1. node --versionNode.js version
    2. npm ls -g --depth=0globally installed npm packages, top level only
  • ldd --version | head -1; openssl version -a | head -2Core library versions (glibc, OpenSSL)

    What each part does

    1. ldd --versionthe C library (glibc) version; matters for binary compatibility and CVEs
    2. openssl version -aOpenSSL version and build date
  • sudo apt install <package>=<version>Install a specific version (Debian / Ubuntu)Caution

    What each part does

    1. <package>=<version>exact version from apt list -a; add --allow-downgrades to go back
  • sudo dnf install <package>-<version>Install a specific version (RHEL / Fedora)Caution

    What each part does

    1. <package>-<version>exact version from dnf list --showduplicates; dnf downgrade to go back
  • sudo apt-mark hold <package>; sudo dnf versionlock add <package>Stop a package from being upgraded

    What each part does

    1. apt-mark holdDebian / Ubuntu: keep the current version (apt-mark unhold to release)
    2. dnf versionlock addRHEL / Fedora: same idea (needs the versionlock plugin)
  • dnf provides '*/<file>'; apt-file search <file>Which package provides a file you don't have?

    What each part does

    1. dnf provides '*/<file>'RHEL family: packages containing that file
    2. apt-file search <file>Debian / Ubuntu (install apt-file and run apt-file update first)
  • ansible all -i <inventory> -m shell -a "rpm -q <package> 2>/dev/null || dpkg-query -W <package>"Check a package version across many servers

    What each part does

    1. ansible all -i <inventory>every host in the inventory
    2. -m shell -a "..."run the command on each one
    3. rpm -q <package> || dpkg-query -W <package>works on both RHEL- and Debian-family hosts

    Tip Without Ansible: for h in <host1> <host2>; do echo "$h: $(ssh $h 'rpm -q <package> 2>/dev/null || dpkg-query -W <package>')"; done

System info9

  • uname -aKernel and architecture

    What each part does

    1. unamesystem information
    2. -aall: kernel name, hostname, release, version, architecture
  • cat /etc/os-releaseWhich Linux distribution and version?

    What each part does

    1. /etc/os-releaseNAME, VERSION_ID, ID of the distro (ubuntu, debian, rhel…)
  • hostname; hostname -IHost name and IP addresses

    What each part does

    1. hostnamethe machine name
    2. -Iall IP addresses of the host
  • uptimeHow long has it been running? Load?

    What each part does

    1. uptimetime since boot, logged-in users, load average over 1/5/15 minutes
  • date; timedatectlDate, time and timezone

    What each part does

    1. datecurrent date and time
    2. timedatectltimezone and whether NTP sync is active
  • nproc; lscpuCPU cores and model

    What each part does

    1. nprocnumber of CPUs available
    2. lscpuCPU model, cores, threads, architecture
  • lsblkDisks and partitions

    What each part does

    1. lsblkblock devices as a tree: disks, partitions, sizes, mount points
  • findmntWhat is mounted where

    What each part does

    1. findmntmounted filesystems as a tree (cleaner than mount)
  • sudo reboot; sudo shutdown -h nowReboot / shut downDestructive

    What each part does

    1. rebootrestart the machine
    2. shutdown -h now-h = halt/power off, now = immediately (or +10 for 10 minutes)

Network basics & SSH10

  • ping -c 4 <host>Is a host reachable?

    What each part does

    1. pingsend ICMP echo requests
    2. -c 4stop after 4 packets (otherwise it runs until Ctrl+C)
  • ssh <user>@<host>Log in to a server

    What each part does

    1. sshsecure shell
    2. <user>@<host>remote user name and host name or IP
  • ssh -p <port> -i <key-file> <user>@<host>SSH with a port and a key file

    What each part does

    1. -p <port>remote port (default 22)
    2. -i <key-file>private key to use
  • ssh <user>@<host> "<command>"Run one command remotely

    What each part does

    1. "<command>"runs on the server, output comes back to you
  • ssh-keygen -t ed25519 -C "<email>"Create an SSH key

    What each part does

    1. ssh-keygengenerate a key pair
    2. -t ed25519key type (ed25519 is the modern default)
    3. -C "<email>"comment stored in the key, to recognise it

    Tip Creates ~/.ssh/id_ed25519 (private, keep secret) and id_ed25519.pub (public).

  • ssh-copy-id <user>@<host>Install your public key on a server

    What each part does

    1. ssh-copy-idappend your public key to ~/.ssh/authorized_keys on the server
  • wget <url>Download a file

    What each part does

    1. wgetdownload to the current folder (curl -O <url> does the same)
  • nc -zv <host> <port>Is a TCP port open?

    What each part does

    1. ncnetcat
    2. -zjust scan, send no data
    3. -vverbose: say "succeeded" or "refused"
  • traceroute <host>Path packets take to a host

    What each part does

    1. traceroutelist every hop (router) on the way; shows where it stops
  • ip aShow IP addresses

    What each part does

    1. ip ashort for ip address: every interface with its IPs

Zip & compress4

  • zip -r <archive>.zip <dir>Zip a folder

    What each part does

    1. zipcreate a .zip archive
    2. -rinclude folders recursively
  • unzip <archive>.zip -d <dir>Unzip into a folder

    What each part does

    1. -d <dir>extract into <dir> instead of the current folder
  • gzip <file>; gunzip <file>.gzCompress / decompress one file

    What each part does

    1. gzip <file>replace <file> with <file>.gz
    2. gunziprestore the original
  • tar -tf <archive>.tar.gzList what is inside a tarball

    What each part does

    1. -tlist contents
    2. -farchive file name

Shell operators (how combinations work)6

  • cmd1 | cmd2Send the output of one command into another

    What each part does

    1. cmd1first command; its normal output (stdout) is captured
    2. |pipe: stdout of the left command becomes the input (stdin) of the right one
    3. cmd2second command, reads that input (e.g. grep, sort, head)
  • cmd > out.txt; cmd >> out.txtSave output to a file (overwrite / append)

    What each part does

    1. >redirect stdout to a file, creating it or truncating it to empty first
    2. ;run the next command after the first, whatever its result
    3. >>append stdout to the end of the file (creates it if missing)
  • cmd > out.log 2>&1Capture errors together with normal output

    What each part does

    1. > out.logstdout (file descriptor 1) goes to out.log
    2. 2>&1make stderr (fd 2) point where stdout points. Order matters: it must come after > out.log

    Tip Short bash form: cmd &> out.log

  • make build && make deploy || echo "failed"Run the next command only if the previous one succeeded / failed

    What each part does

    1. make buildfirst command
    2. &&run the next command only if the previous exited with code 0 (success)
    3. make deployruns only after a successful build
    4. ||run the next command only if the previous exited non-zero (failure)
    5. echo "failed"fallback message
  • kill $(pgrep -f <name>)Use the output of a command as an argument

    What each part does

    1. killsend a signal (TERM by default) to process IDs
    2. $( … )command substitution: run the inner command and paste its output here
    3. pgrep -f <name>print PIDs whose full command line matches <name>
  • cat <list-file> | xargs -r -n 1 <cmd>Pass input lines as arguments to another command

    What each part does

    1. cat <list-file>print the file (one item per line)
    2. |pipe into xargs
    3. xargsbuild and run command lines from its input
    4. -rdon't run the command at all if the input is empty (GNU xargs)
    5. -n 1one input item per command invocation
    6. <cmd>the command to run with each item appended

Processes6

  • ps aux | grep <name>Find a process by name

    What each part does

    1. pssnapshot of current processes
    2. auxBSD-style options (no dash): a = all users, u = user-oriented columns (USER, %CPU, %MEM…), x = include processes without a terminal
    3. |pipe the process list into grep
    4. grep <name>keep only lines containing <name>

    Tip The grep line itself matches too. Use grep "[n]ginx" (brackets on one letter) or pgrep -a <name>.

  • ps aux --sort=-%mem | headTop 10 processes by memory

    What each part does

    1. ps auxall processes, user-oriented columns
    2. --sort=-%memsort by memory share; the leading "-" means descending
    3. | headkeep the first 10 lines (header + top 9)
  • ps -eo pid,user,%cpu,%mem,comm --sort=-%cpu | head -n 15Custom columns sorted by CPU

    What each part does

    1. -eselect every process
    2. -o pid,user,%cpu,%mem,commchoose the output columns: PID, owner, CPU %, memory %, executable name
    3. --sort=-%cpuhighest CPU first
    4. head -n 15first 15 lines
  • top -b -n 1 | head -n 20One-shot top output (for logs or scripts)

    What each part does

    1. toplive process viewer
    2. -bbatch mode: plain text, no interactive screen (works in pipes)
    3. -n 1stop after one refresh
    4. head -n 20summary lines plus the top processes
  • kill <pid>; sleep 5; kill -9 <pid>Stop a process gracefully, then forcefullyCaution

    What each part does

    1. kill <pid>send SIGTERM (15): asks the process to exit and clean up
    2. sleep 5give it time to shut down
    3. kill -9 <pid>send SIGKILL: cannot be caught, ends it immediately (no cleanup)
  • free -hMemory usage in human units

    What each part does

    1. freeshow RAM and swap usage
    2. -hhuman-readable units (Mi, Gi). Look at the "available" column, not "free"
  • grep -rn "<text>" <dir>Search text in all files under a folder

    What each part does

    1. grepprint lines matching a pattern
    2. -rrecurse into sub-directories
    3. -nshow the line number of each match
    4. "<text>"the pattern (quote it if it has spaces or special characters)
    5. <dir>where to start searching
  • grep -rni --include="*.yaml" "<pattern>" <dir>Case-insensitive search in one file type only

    What each part does

    1. -r -nrecursive, with line numbers
    2. -iignore upper/lower case
    3. --include="*.yaml"only search files whose name matches the glob
    4. "<pattern>"regular expression to find

    Tip Useful extras: -l (only file names), -v (lines that do NOT match), -w (whole word), -C 3 (3 lines of context).

  • find <dir> -name "*.log" -mtime +7 -deleteFind and delete log files older than 7 daysDestructive

    What each part does

    1. find <dir>walk the directory tree starting at <dir>
    2. -name "*.log"file name matches the pattern (quoted so the shell does not expand it)
    3. -mtime +7last modified more than 7 days ago
    4. -deletedelete each match

    Tip Run it with -print instead of -delete first to see what would go.

  • find <dir> -type f -size +100MFind big files

    What each part does

    1. -type fregular files only (d = directories)
    2. -size +100Mlarger than 100 MiB ("+" = more than, "-" = less than)
  • find <dir> -name "*.tmp" -print0 | xargs -0 rm -fRun a command on every found file (safe with spaces)Destructive

    What each part does

    1. -print0print each name ending with a NUL byte instead of a newline
    2. |pipe the names to xargs
    3. xargs -0read NUL-separated names, so spaces/newlines in names are safe
    4. rm -fremove the files, no prompts
  • tail -F <file> | grep --line-buffered "<word>"Follow a log and show only matching lines

    What each part does

    1. tailshow the end of a file
    2. -Ffollow new lines and keep following when the file is rotated or recreated
    3. |stream new lines into grep
    4. grep --line-bufferedprint each match immediately instead of buffering
    5. "<word>"text to look for, e.g. ERROR
  • sed -n '<start>,<end>p' <file>Show lines N to M of a file

    What each part does

    1. sedstream editor
    2. -ndon't print every line automatically
    3. '<start>,<end>p'address range (line numbers) + p = print those lines
  • sed -i.bak 's/<old>/<new>/g' <file>Replace text in a file in place (keep a backup)Caution

    What each part does

    1. -i.bakedit the file in place and save the original as <file>.bak
    2. s/<old>/<new>/substitute: regex <old> → <new>
    3. greplace every match on a line, not just the first

Text processing pipelines4

  • sort <file> | uniq -c | sort -rn | headCount duplicate lines, most frequent first

    What each part does

    1. sort <file>sort lines so duplicates sit next to each other
    2. uniq -ccollapse adjacent duplicates and prefix each with its count
    3. sort -rnsort by that number (-n numeric) in reverse order (-r)
    4. headtop 10
  • awk '{print $1}' access.log | sort | uniq -c | sort -rn | headTop client IPs in an access log

    What each part does

    1. awk '{print $1}'print the first whitespace-separated field of every line (the client IP)
    2. sort | uniq -cgroup identical IPs and count them
    3. sort -rn | headhighest counts first, top 10
  • grep -c "<pattern>" <file>; wc -l <file>Count lines / matches

    What each part does

    1. grep -ccount matching lines instead of printing them
    2. wc -lcount all lines in the file
  • sort -t: -k3,3n /etc/passwdSort a delimited file by a numeric column

    What each part does

    1. -t:fields are separated by ":"
    2. -k3,3sort key is field 3 only
    3. ncompare that key as a number

Disk3

  • df -hT; df -iDisk space per filesystem (and inodes)

    What each part does

    1. dfreport filesystem usage
    2. -hhuman-readable sizes
    3. -Tshow the filesystem type
    4. df -iinode usage instead of space. A disk can be "full" on inodes
  • du -sh * | sort -rh | headBiggest items in the current folder

    What each part does

    1. duestimate file/directory space
    2. -sone total per argument
    3. -hhuman-readable sizes
    4. *every entry in the current directory (shell glob)
    5. sort -rhsort human sizes (-h knows 2K < 1G), largest first (-r)
    6. headtop 10
  • du -xh -d 1 <dir> | sort -rh | head -n 15Folder sizes one level deep, same filesystem

    What each part does

    1. -xdon't cross into other mounted filesystems
    2. -hhuman-readable
    3. -d 1only show totals one level below <dir> (same as --max-depth=1)
    4. sort -rh | head -n 15largest 15

Network5

  • ss -tulpnWhich process listens on which port

    What each part does

    1. sssocket statistics (modern netstat)
    2. -tTCP sockets
    3. -uUDP sockets
    4. -llistening sockets only
    5. -pshow the owning process (needs sudo for other users’ processes)
    6. -nnumeric ports and addresses, no name lookups
  • sudo lsof -i :<port>Who is using a port

    What each part does

    1. lsoflist open files (sockets are files too)
    2. -ionly network sockets
    3. :<port>filter to that port
  • ip -br addr; ip routeInterfaces and routes

    What each part does

    1. ip -br addrevery interface with its addresses, one line each (-br = brief)
    2. ip routerouting table, including the default gateway
  • curl -sS -o /dev/null -w "%{http_code} %{time_total}s\n" <url>Check an HTTP endpoint: status code and time

    What each part does

    1. -ssilent: no progress bar
    2. -Sbut still show errors
    3. -o /dev/nullthrow away the response body
    4. -w "…"print a custom line after the request: %{http_code} = status, %{time_total} = seconds
  • curl -fsSL <url> -o <file>Download a file, following redirects, failing on HTTP errors

    What each part does

    1. -ffail (non-zero exit, no output) on HTTP 4xx/5xx
    2. -s -Squiet, but show errors
    3. -Lfollow redirects
    4. -o <file>write the body to <file>

Services & logs (systemd)6

  • systemctl status <unit> --no-pager -lStatus and recent logs of a service

    What each part does

    1. systemctl status <unit>state, PID, last exit code and the last log lines
    2. --no-pagerprint directly instead of opening less
    3. -ldon't truncate long lines
  • sudo systemctl enable --now <unit>Start at boot and start now

    What each part does

    1. enablecreate the links so the unit starts at boot
    2. --nowalso start it right away
  • sudo systemctl daemon-reload && sudo systemctl restart <unit>Reload unit files after editing them

    What each part does

    1. daemon-reloadre-read unit files (does not restart services)
    2. &&only if that worked…
    3. restart <unit>stop then start the service
  • journalctl -u <unit> -f -n 100Follow a service log

    What each part does

    1. -u <unit>only messages from that unit
    2. -ffollow new entries
    3. -n 100start with the last 100 lines
  • journalctl -p err -b --no-pagerErrors since boot

    What each part does

    1. -p errpriority "err" and more severe (crit, alert, emerg)
    2. -bcurrent boot only (-b -1 = previous boot)
    3. --no-pagerplain output
  • journalctl -u <unit> --since "1 hour ago" --until nowLogs in a time window

    What each part does

    1. --sincestart time: absolute ("2026-11-20 10:00") or relative ("1 hour ago", "yesterday")
    2. --untilend time

Archives & copying4

  • tar -czvf <name>.tar.gz <dir>Create a gzip tarball

    What each part does

    1. -ccreate an archive
    2. -zcompress with gzip
    3. -vlist files as they are added
    4. -f <name>.tar.gzarchive file name (must come right after f)
  • tar -xzvf <name>.tar.gz -C <dest>Extract a tarball into a folder

    What each part does

    1. -xextract
    2. -z -v -fgzip, verbose, archive file
    3. -C <dest>change to <dest> before extracting
  • rsync -avzn --delete <src>/ <user>@<host>:<dest>/Sync a folder to a server (preview first)Caution

    What each part does

    1. -aarchive mode: recursive, keep permissions, times, owner, symlinks
    2. -vverbose
    3. -zcompress during transfer
    4. -ndry run: show what would change. Remove it to really sync
    5. --deletedelete files on the destination that are not in the source
    6. <src>/trailing slash = copy the folder’s contents, not the folder itself
  • scp -r -P <port> <src> <user>@<host>:<path>Copy a folder to a server over SSH

    What each part does

    1. -rcopy directories recursively
    2. -P <port>SSH port (capital P; lowercase -p means preserve times)
    3. <user>@<host>:<path>remote destination

Firewall (ufw, firewalld, iptables, nftables)7

  • sudo ufw status verboseFirewall status and rules (Ubuntu ufw)

    What each part does

    1. ufw statusactive or not, and each allow/deny rule
    2. verbosealso default policies and logging level
  • sudo ufw allow <port>/tcpAllow a port (ufw)Caution

    What each part does

    1. ufw allowadd an allow rule (ufw allow from <ip> to any port <port> to restrict the source)
    2. <port>/tcpport and protocol
  • sudo firewall-cmd --list-allFirewall rules (RHEL firewalld)

    What each part does

    1. firewall-cmd --list-allthe default zone's services, ports, rich rules and interfaces
  • sudo firewall-cmd --permanent --add-port=<port>/tcp && sudo firewall-cmd --reloadOpen a port permanently (firewalld)Caution

    What each part does

    1. --permanentsave to config (without it the rule is lost on reload)
    2. --add-port=<port>/tcpopen the port in the default zone (or --add-service=https)
    3. --reloadapply the saved config
  • sudo iptables -L -n -v --line-numbersList iptables rules with counters

    What each part does

    1. -Llist rules of the filter table
    2. -nnumeric, no DNS lookups
    3. -vpacket/byte counters and interfaces
    4. --line-numbersrule numbers, for deleting by number
  • sudo iptables -t nat -L -n -vList NAT rules (port forwards, Docker, Kubernetes)

    What each part does

    1. -t natthe NAT table: DNAT port forwards and MASQUERADE rules
  • sudo nft list rulesetShow the full nftables ruleset

    What each part does

    1. nft list rulesetevery table, chain and rule (newer distros use nftables under firewalld and iptables-nft)

Scheduling: cron & systemd timers6

  • crontab -l; crontab -eList and edit your cron jobs

    What each part does

    1. crontab -lshow your user's cron jobs (sudo crontab -l -u <user> for others)
    2. crontab -eedit them in $EDITOR
  • */5 * * * * /usr/local/bin/<script> >> /var/log/<script>.log 2>&1Cron line format

    What each part does

    1. */5 * * * *minute hour day-of-month month day-of-week: here every 5 minutes
    2. /usr/local/bin/<script>use full paths: cron has a minimal PATH
    3. >> <log> 2>&1append output and errors to a log, otherwise they are mailed or lost
  • ls /etc/cron.d /etc/cron.daily /etc/cron.hourly; cat /etc/crontabSystem-wide cron jobs

    What each part does

    1. /etc/cron.djob files from packages and admins (with a user field)
    2. /etc/cron.daily, hourly...scripts run by run-parts at those intervals
  • journalctl -u cron -u crond --since todayDid cron run my job?

    What each part does

    1. journalctl -u cron -u crondcron daemon logs (cron on Debian, crond on RHEL); or grep CRON /var/log/syslog
    2. --since todayonly today
  • systemctl list-timers --allList systemd timers and when they run next

    What each part does

    1. list-timersevery timer: next run, last run, the unit it starts
    2. --allinclude inactive timers
  • echo '<command>' | at 02:00Run a command once at a later time

    What each part does

    1. at 02:00run once at 2 AM (also: at now + 30 minutes); atq lists, atrm removes

Storage, mounts & LVM10

  • lsblk -fDisks, partitions and filesystems

    What each part does

    1. lsblkblock devices as a tree: disks, partitions, LVM volumes
    2. -fadd filesystem type, label, UUID and mount point
  • sudo mount <device> <mount-point>Mount a filesystem

    What each part does

    1. mount <device>e.g. /dev/sdb1 or /dev/mapper/vg-data
    2. <mount-point>existing empty directory, e.g. /mnt/data
  • sudo findmnt --verify && sudo mount -aTest /etc/fstab before rebooting

    What each part does

    1. findmnt --verifycheck fstab syntax, devices and filesystem types
    2. mount -amount everything in fstab now; a typo here would otherwise stop the next boot
  • sudo umount <mount-point> || sudo lsof +f -- <mount-point>Unmount, and find what keeps it busy

    What each part does

    1. umountunmount
    2. lsof +f -- <mount-point>processes with files open there (target is busy)
  • sudo mkfs.ext4 -L <label> <device>Create a filesystem on a new diskDestructive

    What each part does

    1. mkfs.ext4format as ext4 (mkfs.xfs for XFS): erases the device
    2. -L <label>filesystem label
  • sudo growpart <disk> <partition-number> && sudo resize2fs <partition>Grow a partition and filesystem after enlarging a cloud diskCaution

    What each part does

    1. growpart /dev/xvda 1extend partition 1 to fill the disk (cloud-guest-utils)
    2. resize2fs <partition>grow an ext4 filesystem; for XFS: xfs_growfs <mount-point>
  • sudo pvs; sudo vgs; sudo lvsLVM overview

    What each part does

    1. pvsphysical volumes (disks in LVM)
    2. vgsvolume groups and their free space
    3. lvslogical volumes and sizes
  • sudo lvextend -r -L +<size>G /dev/<vg>/<lv>Extend a logical volume and its filesystemCaution

    What each part does

    1. lvextendgrow a logical volume
    2. -ralso resize the filesystem in one step
    3. -L +<size>Gadd this much (or -l +100%FREE for all free space)
  • swapon --show; sudo fallocate -l 2G /swapfile && sudo chmod 600 /swapfile && sudo mkswap /swapfile && sudo swapon /swapfileShow swap, and add a swap file

    What each part does

    1. swapon --showactive swap devices and usage
    2. fallocate -l 2G /swapfilecreate a 2 GB file
    3. chmod 600only root may read it
    4. mkswap / swaponformat it as swap and enable it (add to fstab to keep it)
  • df -iOut of inodes? (disk full with free space left)

    What each part does

    1. df -iinode usage per filesystem; 100% means no new files even if space is free (millions of tiny files)

Kernel, hardware & limits8

  • sudo dmesg -T | tail -50Kernel messages with readable times

    What each part does

    1. dmesgkernel ring buffer: hardware errors, OOM killer, disk and network driver messages
    2. -Thuman-readable timestamps
    3. | tail -50the latest 50 lines
  • sudo dmesg -T | grep -i -E 'killed process|out of memory'Did the OOM killer kill something?

    What each part does

    1. grep -i -E '...'lines where the kernel killed a process to free memory, with its name and memory use
  • lscpu; lspci; sudo dmidecode -t systemHardware overview

    What each part does

    1. lscpuCPU model, cores, threads, virtualization
    2. lspciPCI devices: NICs, GPUs, storage controllers
    3. dmidecode -t systemvendor, model and serial number
  • sysctl <key>; sudo sysctl -w <key>=<value>Read and change kernel parametersCaution

    What each part does

    1. sysctl <key>e.g. vm.swappiness, net.ipv4.ip_forward, fs.file-max
    2. sysctl -w <key>=<value>change it now; put it in /etc/sysctl.d/*.conf to keep it after reboot
  • ulimit -n; cat /proc/<pid>/limitsOpen-file and process limits

    What each part does

    1. ulimit -nmax open files for this shell (Too many open files means you hit it)
    2. /proc/<pid>/limitsthe actual limits of a running process (systemd services set LimitNOFILE)
  • lsmod | grep <module>; sudo modprobe <module>Kernel modules

    What each part does

    1. lsmodloaded modules
    2. modprobe <module>load a module with its dependencies (e.g. br_netfilter for Kubernetes)
  • timedatectlTime, timezone and NTP sync

    What each part does

    1. timedatectllocal time, UTC, timezone and whether the clock is NTP-synchronized (clock skew breaks TLS and tokens)
  • uptimeUptime and load average

    What each part does

    1. uptimehow long since boot, users, and 1/5/15-minute load averages (compare with CPU count)

Performance & tracing10

  • vmstat 1 5CPU, memory, swap and I/O wait every second

    What each part does

    1. vmstatr (run queue), free memory, si/so (swapping), wa (I/O wait), us/sy/id CPU
    2. 1 5every 1 second, 5 times (the first line is the average since boot)
  • iostat -xz 1Disk I/O per device

    What each part does

    1. iostatdisk statistics (sysstat package)
    2. -xextended: %util, await (latency), r/s, w/s
    3. -zhide idle devices
    4. 1refresh every second
  • mpstat -P ALL 1CPU usage per core

    What each part does

    1. mpstatCPU statistics (sysstat)
    2. -P ALLevery core, to spot one core at 100%
    3. 1every second
  • pidstat -u -r -d 1CPU, memory and I/O per process over time

    What each part does

    1. pidstatper-process statistics (sysstat)
    2. -u -r -dCPU, memory (faults, RSS) and disk I/O
    3. 1every second
  • sudo iotop -oPaWhich processes do the most disk I/O?

    What each part does

    1. iotoptop for disk I/O
    2. -oonly processes actually doing I/O
    3. -Pper process, not per thread
    4. -aaccumulated totals
  • ps -eo pid,user,%mem,rss,cmd --sort=-rss | head -15Top memory users

    What each part does

    1. ps -eo ...pick columns: PID, user, % of RAM, resident memory in KB, command
    2. --sort=-rssbiggest memory first
    3. | head -15top 14 plus the header
  • sudo strace -f -tt -p <pid> -e trace=network,fileTrace what a process is doing (system calls)

    What each part does

    1. strace -p <pid>attach to a running process
    2. -ffollow its threads and children
    3. -tttimestamps with microseconds
    4. -e trace=network,fileonly network and file calls (drop it to see everything)

    Tip Slows the process down a lot; use briefly in production.

  • sudo perf topLive CPU profile of the whole system

    What each part does

    1. perf topfunctions using the most CPU right now, across kernel and user space
  • sar -n DEV 1Network traffic per interface

    What each part does

    1. sar -n DEVpackets and KB per second per interface (sysstat)
    2. 1every second; sar without a count reads history if sysstat collection is enabled
  • watch -n 2 -d '<command>'Re-run a command every few seconds

    What each part does

    1. watchrun the command repeatedly, full-screen
    2. -n 2every 2 seconds
    3. -dhighlight what changed

TLS & certificates (openssl)8

  • openssl s_client -connect <host>:443 -servername <host> -showcerts </dev/nullShow a server's certificate and chain

    What each part does

    1. s_client -connect <host>:443open a TLS connection
    2. -servername <host>send SNI, so you get the right certificate on shared IPs
    3. -showcertsprint every certificate the server sends
    4. </dev/nullclose the connection right after the handshake
  • openssl s_client -connect <host>:443 -servername <host> </dev/null 2>/dev/null | openssl x509 -noout -subject -issuer -datesWhen does a site's certificate expire?

    What each part does

    1. openssl s_client ...fetch the certificate
    2. | openssl x509 -nooutparse it without printing the encoded certificate
    3. -subject -issuer -dateswho it is for, who signed it, notBefore and notAfter
  • openssl x509 -in <cert>.pem -noout -textRead a certificate file

    What each part does

    1. x509 -in <cert>.pema PEM certificate file
    2. -noout -textfull details: subject, SANs (DNS names), validity, key size
  • openssl x509 -noout -pubkey -in <cert>.pem | sha256sum; openssl pkey -pubout -in <key>.pem | sha256sumDoes this key belong to this certificate?

    What each part does

    1. x509 -pubkeypublic key from the certificate
    2. pkey -puboutpublic key derived from the private key
    3. sha256sumthe two hashes must be identical
  • openssl req -new -newkey rsa:2048 -nodes -keyout <name>.key -out <name>.csr -subj "/CN=<domain>"Create a private key and a CSR

    What each part does

    1. req -newnew certificate signing request
    2. -newkey rsa:2048 -nodesgenerate a 2048-bit key, not encrypted with a passphrase
    3. -keyout / -outwhere to write the key and the CSR
    4. -subj "/CN=<domain>"subject; add -addext "subjectAltName=DNS:<domain>" for SANs
  • openssl req -x509 -newkey rsa:2048 -nodes -days 365 -keyout <name>.key -out <name>.crt -subj "/CN=<domain>"Self-signed certificate for testing

    What each part does

    1. req -x509output a self-signed certificate instead of a CSR
    2. -days 365valid for a year
  • openssl verify -CAfile <ca-bundle>.pem <cert>.pemCheck a certificate against a CA bundle

    What each part does

    1. openssl verifyOK if the chain validates; otherwise the reason (expired, unable to get issuer)
    2. -CAfiletrusted CA and intermediates
  • openssl s_client -connect <host>:443 -tls1_2 </dev/null; openssl s_client -connect <host>:443 -tls1_3 </dev/nullWhich TLS versions does a server accept?

    What each part does

    1. -tls1_2 / -tls1_3force one protocol version; a handshake failure means it's not supported

Packet capture & network debugging10

  • sudo tcpdump -i any -nn port <port>Capture traffic on a port

    What each part does

    1. tcpdumppacket capture
    2. -i anyall interfaces
    3. -nndon't resolve names or ports
    4. port <port>filter: only traffic on that port (also host <ip>, tcp, udp)
  • sudo tcpdump -i <interface> -w <file>.pcap -c 10000 host <ip>Save a capture for Wireshark

    What each part does

    1. -w <file>.pcapwrite raw packets to a file
    2. -c 10000stop after 10,000 packets
    3. host <ip>only traffic to or from this IP
  • ip route get <ip>Which route and source IP would be used?

    What each part does

    1. ip route getthe exact route, gateway, interface and source address the kernel would use
  • mtr -rwc 50 <host>Path and packet loss to a host

    What each part does

    1. mtrtraceroute and ping combined, per hop
    2. -r -wreport mode with wide (untruncated) host names
    3. -c 5050 probes per hop
  • nmap -Pn -p 1-1024 <host>Scan a host's open ports

    What each part does

    1. nmapport scanner (only scan hosts you're allowed to)
    2. -Pnskip the ping check (many hosts block ping)
    3. -p 1-1024port range (or -p 22,80,443)
  • ss -sSocket summary

    What each part does

    1. ss -stotals of TCP states: established, time-wait, orphaned; spot connection leaks
  • ss -tn state established | awk 'NR>1 {split($4,a,":"); print a[1]}' | sort | uniq -c | sort -rn | headConnections per remote IP

    What each part does

    1. ss -tn state establishedopen TCP connections, numeric
    2. awk '...'take the peer address column and strip the port
    3. sort | uniq -c | sort -rn | headcount per IP, busiest first
  • ip neighARP / neighbour table

    What each part does

    1. ip neighIP to MAC mappings; FAILED or INCOMPLETE entries point to layer 2 problems
  • curl -sv --resolve <host>:443:<ip> https://<host>/Test a URL against a specific IP (skip DNS)

    What each part does

    1. --resolve <host>:443:<ip>use this IP for that host and port, keeping the right SNI and Host header
    2. -svquiet progress, verbose headers and TLS
  • nc -l <port>Listen on a port to test reachability

    What each part does

    1. nc -l <port>listen; from another machine nc -zv <host> <port> or curl shows whether traffic gets through

Terminal tools (tmux, jq, background jobs)8

  • tmux new -A -s <name>Start or reattach a tmux session

    What each part does

    1. tmux new -s <name>new named session that survives SSH disconnects
    2. -Aattach instead if it already exists

    Tip Detach with Ctrl+B then D; list with tmux ls.

  • <command> | jq '.items[] | {name: .metadata.name, phase: .status.phase}'Pretty-print and filter JSON

    What each part does

    1. | jq '...'JSON processor
    2. .items[]iterate over an array
    3. {name: ..., phase: ...}build a smaller object with just those fields
  • jq -r '.[] | select(.state=="running") | .name' <file>.jsonRaw values from JSON for scripts

    What each part does

    1. -rraw strings, no quotes
    2. select(.state=="running")keep only matching items
    3. .nameprint one field
  • yq '.spec.replicas' <file>.yaml; yq -i '.spec.replicas = 3' <file>.yamlRead or edit YAML

    What each part does

    1. yq '.path'read a value (jq syntax for YAML)
    2. yq -i '...'edit the file in place
  • nohup <command> > <log> 2>&1 &Keep a command running after logout

    What each part does

    1. nohupignore the hangup signal sent when you log out
    2. > <log> 2>&1send output and errors to a log
    3. &run in the background; jobs and fg to manage it
  • timeout 30s <command>Stop a command that runs too long

    What each part does

    1. timeout 30skill the command after 30 seconds; exit code 124 if it timed out
  • cat <list> | xargs -P 8 -I{} <command> {}Run commands in parallel

    What each part does

    1. xargs -P 8up to 8 at a time
    2. -I{}replace {} in the command with each input line
  • until <command>; do echo retrying; sleep 5; doneRetry a command until it succeeds

    What each part does

    1. until <command>loop while the command fails
    2. sleep 5wait between attempts

My DevOps Playbook by Angelo John Calleja

New runbook

GitHub not connected

Saving is handled by the site: the GitHub token is stored in Cloudflare, not in your browser. Enter the editor password (the EDITOR_PASSWORD secret) to unlock saving in this browser.

Saving commits to gelogrammer/My_DevOps_Playbook. Create a fine-grained token with access to only this repo andContents: Read and write, then paste it here. It is stored only in this browser.

src/content/docs/…