Task → recipe
Recipes: 522. A task and the commands that solve it.
Basic commands
- Examples
- Commands
- Time formats Access is controlled by /etc/at.allow / /etc/at.deny (who can queue jobs).
- Conditions and loops The [ -f ], [ -z ] and -eq checks are in test-conditions.
- Default values and parts of a path
- Check the syntax without running shellcheck goes deeper:
- File names with spaces A loop over ls or find output inside $( ) splits names on spaces.
- Find what will execute {#resolve-command} Inspect all definitions of the name.
- Inspect command-line editing mode {#interactive} set -o lists option states, including emacs and vi.
- Edit the command line with keys {#line-editing} In emacs mode (on by default), you edit the line before Enter with these keys:
- Understand startup files {#startup} An interactive non-login shell reads ~/.bashrc.
- Examples cd - is the most common trick:
- Tricks In bash you can turn on shopt -s autocd — then typing a bare path without cd goes there directly.
- Formats Specifiers:
- Timestamps and arithmetic
- Writing to a file
- When to use printf echo behaves differently across shells (especially -e/-n).
- Where to save it (login vs. non-login) File When it's read ~/.bashrc interactive non-login shells (a new terminal/tab) ~/.profile / ~/.bash_profile login shells (SSH login/console login)…
- Test a command in if {#if-command} if reads the command's code itself; $?
- Save the code before it is overwritten {#save-code} Every command overwrites $?
- Exit with an error message The message goes to standard error (>&2) and the code is non-zero, so both a person and the calling program understand the script.
- curl's code and the HTTP response {#curl-http-code} curl's code answers whether an exchange with the server took place.
- Your own codes for different failures The usual convention:
- The code of every pipeline stage
- A crontab line that never overlaps A run that lands on a still-running previous one is quietly skipped.
- A lock inside the script exec 9>file opens descriptor 9 for the whole script, and flock -n 9 locks it.
- A systemd service systemd never starts a second copy of the same unit on its own:
- Wait, but not forever
- Who holds the lock lsof also shows the child process:
- man man sections:
- Other places to look
- Patterns Pattern Meaning * any string (including empty), except / ?
- Glob vs. regex glob is for filenames in the shell; * means "anything".
- Identify the server before making changes {#identify} Check the node name alongside the user identity.
- Check resolution of the current name {#resolution} getent queries the configured system name sources.
- Compare resolved and interface addresses {#addresses} Different name and interface configuration can legitimately produce different results.
- A file name with a space or special character The easiest way is to type the start of the name and press Tab:
- An argument that starts with a dash
- Several commands on one line
- A long command over several lines A \ at the end of a line continues the command on the next one.
- Navigation Tab — switch between the left and right panel.
- F-keys Key Action F3 view a file (mcview) F4 edit it (mcedit) F5 copy the selection to the other panel F6 move / rename F7 create a directory F8 delete F9 the top…
- Editor and SFTP Access a remote machine right from a panel (an SSH shell link):
- Keyboard shortcuts ^O = Ctrl+O, M-W = Alt+W.
- Output and errors in separate files
- The order of 2>&1 matters The shell reads redirections left to right.
- Process output with a chain of commands Each stage does one thing:
- Write to a file that needs root sudo cmd > /etc/file won't work:
- Multi-line input right into a command
- Empty a log without deleting the file If a process keeps the log open, rm won't free the space, but emptying will.
- Find out which stage of a pipeline failed
- Format Specifier Meaning %s %d %f string / integer / float %-Ns %Nd width N (- = left-aligned) %.Nf N digits after the decimal point %05d leading zeros %x %o hex /…
- More recipes
- Check location before file operations {#locate} Inspect location and contents separately:
- Resolve a physical path {#resolve} Compare both results after entering through an existing symbolic link.
- Identify which pwd is selected {#implementation} Bash may select a builtin, function, or alias.
- Hotkeys The prefix is Ctrl+a, then a key:
- Useful ~/.screenrc (common settings):
- A check before running or in CI With -S warning, info and style findings are neither printed nor counted:
- Silence one finding in one place The comment covers the next command.
- Silence a finding for a whole directory A .shellcheckrc file in the script's directory or above it:
- The script sources another file Without -x, shellcheck prints SC1091 … Not following and does not see the functions from the sourced file.
- Look at the ready-made fixes Only simple findings come with a fix:
- Validate a script argument $# is the number of arguments.
- Compare a number taken from command output -ge wants a bare number.
- Patterns and regular expressions With day=2026-10-20 the second condition prints year 2026, month 10:
- Several conditions at once
- Hotkeys
- Report the running kernel release {#kernel-release} Record the actual result rather than copying a documentation example.
- Separate kernel and distribution identity {#distribution} Compare independent sources.
- Inspect machine architecture and node name {#machine} Architecture and node name are separate properties; neither is the user name.
- Load average uptime shows three numbers — the average length of the run queue over 1, 5, 15 minutes:
- Who and from where
- Quitting and saving
- Navigation and editing
- Useful bits
- Examples Quote a command that has a pipeline/wildcard (watch 'ss | grep x'), otherwise | and * apply to watch itself, not the command.
- Examples A reliable "does this command exist" check in a script:
- Check the current identity {#current-user} Compare the name with the numeric identity.
- Inspect a sudo invocation {#sudo-context} The training VM permits sudo.
- Inspect another account {#other-account} Use id to inspect student; whoami does not accept a user operand.
- Safe with file names Spaces and newlines in file names break a naive xargs.
Files and directories
- Navigation Paths:
- Files and directories rm has no trash can.
- Viewing text Pipes and redirection:
- Terminal and copy-paste
- Back up a config before editing -a keeps the owner and permissions, so the backup can be put back as is.
- A directory into an existing directory, and "into" it The same command gives different results depending on whether dst exists.
- Copy many files into one directory
- Keep the previous version
- Between machines cp works within one machine.
- Examples
- Conditions
- Actions {} + batches arguments (faster), {} \; runs one at a time.
- History: log -p, show, blame {#history} The /etc/demo repository with three commits by two authors:
- Undo a change and a commit: restore, revert, reset {#revert} What to undo Command History an uncommitted change to a file git restore site.conf unchanged one commit git revert --no-edit <commit> a new commit on top…
- A root-owned repository: sudo git {#sudo-git} Files in /etc belong to root, and so does a repository in /etc/nginx.
- A remote repository: fetch, pull, push {#remote} A bare repository is history only, with no working files:
- Shelve a change: stash {#stash} git stash moves uncommitted changes to a separate store and brings the files back to the last commit — so you can get other people's commits when pull refuses…
- Conflict {#conflict} A conflict means both sides changed the same lines, and git does not know which version to keep.
- Branches
- Examples Argument order is like cp:
- Symlink vs hard Symlink (-s) Hard link Points to a directory yes no Across filesystems yes no Target deleted a "broken" symlink data survives as long as any name remains Shown…
- Find the most recently changed file
- See a directory's own permissions, not its files Without -d the command lists what is inside, and the directory's own permissions stay out of view.
- Only directories or only files
- Numeric UID and GID instead of names Useful when a file belongs to a deleted user:
- Ubuntu's short aliases Ubuntu's ~/.bashrc already defines alias ll='ls -alF', alias la='ls -A' and alias l='ls -CF'.
- rmdir rmdir deliberately only removes empty directories — that's a safety net.
- Rename a file in another directory without going there
- Move all files matching a pattern The shell expands *.log (see globbing).
- Rename many files: .txt → .md ${f%.txt} cuts off the extension; the quotes keep names with spaces intact.
- Replace a live file safely Within one filesystem mv replaces the file atomically:
- In scripts The classic case is finding the script's own directory, so paths don't depend on where it was run from:
- Backup and restore
- Maintenance and scheduling In cron or a systemd timer — backup plus forget --prune on a schedule.
- Check a pattern before deleting The shell expands the pattern (see globbing), so ls with the same pattern shows exactly the list rm will get.
- Delete old files by age rm can't select by date or size — that's find's job.
-
Guard
rm -rfagainst an empty variable ${VAR:?} stops the command if the variable is empty or unset. - Delete a file with a strange name
- The trailing slash matters! A trailing slash on the source means "contents".
- Commands
- Examples Common -c format fields:
- Three timestamps atime (%x) — last access (read).
- Commands -sfn matters when replacing a symlink to a directory:
- Symlink vs hard Symlink (-s) Hard Points to a directory yes no Across filesystems yes no Target deleted "broken" data survives as long as any name remains Shown in ls -l ->…
- Commands
Text and search
- Write a short file without an editor Quoting EOF turns off expansion:
- Find invisible characters ^M$ at line ends means Windows line breaks (\r\n).
- Join parts and check the result
- Search a file without cat cat file | grep error works, but the extra process isn't needed:
- User names and their shells
- Addresses from a web server log The first word of an nginx log line is the client address.
- A column from a CSV file If CSV values contain commas inside quotes, cut will not understand them:
- Everything except one field
- Skip lines without the delimiter Without -s, a line with no delimiter is printed whole.
- Commands
- Examples
- Examples
- Investigate stale command resolution {#stale-path} Compare the results.
- Remove just one entry {#one-entry} The first call remembers the discovered path, the second displays it, and the third removes the entry.
- Fix the correct shell context {#current-shell} Clear the cache in the shell where the problem occurs.
- The five largest files in a directory
- The processes using the most memory
- Peek at a file without opening it all
- Lines N to M
- Filters
- Examples and assembly
- Find an error in a long log Search is case-sensitive.
- Keep only the lines you need on screen Inside less, type &Failed and Enter:
- A table with long lines
- Colored output
- Open what you're reading in an editor The v key opens the current file in the default editor — on Ubuntu that's usually nano.
- A word in any case and spelling
- An IP address
- A config without comments and empty lines
- Swap parts of a line Groups ( ) remember parts of the match; \1 and \2 put them into the replacement.
- Preview a replacement, then edit {#preview} diff shows every changed line before and after:
- Delete lines
- Replace a whole line or add one next to it
- One edit across many files The list of files first, the edit second:
- Filter and count in awk
- Which lines occur most often The first sort groups equal addresses together, uniq -c counts them, the second sort -rn puts the largest counts on top, and head keeps ten.
- A table by a numeric field
- Sizes with K, M, G -n reads 512M as 512 and 1G as 1, which gives the wrong order.
- Several keys
- Versions and numbered file names
- Write the result back to the same file sort names.txt > names.txt leaves an empty file; -o writes only after reading.
- Check whether a file is sorted
- sort / uniq
- cut / tr / wc / more
- Parsing logs and tables
- Follow a log and see only errors --line-buffered makes grep print matches right away instead of in batches.
- Skip the header line
- The last lines of several logs at once
- Stop following when a process ends
- Examples
- Why sudo tee This is the main reason to know tee.
- Top addresses in a web server log This answers "who sent the most requests":
- How many distinct values
- Find duplicates in a list
- Compare only part of the line -f N skips N blank-separated fields; -w N compares the first N characters.
- How many lines contain an error
- How many files are in a directory ls | wc -l counts too, but skips hidden files, and ls -l | wc -l adds the total line.
- How many distinct values
- Several files at once
- The longest line
Users and permissions
- Separate observation from modification {#inspect-first} First confirm that the name identifies the intended user.
- Set a past date in a training lab {#expire-training-account} Only after labpaused has been prepared and the exercise requests it:
- Check the actual access path {#check-access-path} The chage report shows local settings.
- chmod Two syntaxes:
- chown
- chgrp chgrp is the same as chown :group, but shorter and more explicit about intent:
- umask umask is a mask whose bits the kernel clears from the default permissions when creating a file (usually 666) or a directory (777).
- Commands
- mask In getfacl output, the mask::
- Numbers and symbols Octal Permissions Typically for 644 rw-r--r-- regular files 600 rw------- secrets, keys 755 rwxr-xr-x scripts, binaries, directories 700 rwx------ private…
- Special bits The three special bits and a team's shared directory are covered in Special permission bits.
- Find where a service loses access Run as the service, namei stops exactly at the part it can't pass:
- Compare the parts of a path by hand ls with -d and stat show the same one by one — handy when there are few parts.
- Where a path really leads Without -l, namei shows only types and expands each link with an indent:
- Assign the training account's shell {#set-training-shell} Only for a prepared labsvc, when the exercise requests this change:
- Demonstrate the program's refusal {#demonstrate-refusal} The message may depend on locale and system configuration.
- Test the restriction's boundary {#uid-still-usable} When permitted by sudo policy:
- A temporary password for a new colleague
- Block login without deleting the account passwd -l closes only password login:
- Passwords for several users at once chpasswd reads name:password pairs.
- A team directory Check:
- Fix files that are already there setgid works on new files.
- Find setuid and setgid programs A clean system has a dozen or so:
- Change your mask for good
- A team's shared directory For files to also get the directory's group instead of yours, the directory needs the setgid bit.
- A service's mask A line in the unit or in a drop-in (sudo systemctl edit app) — see systemd.
- Create one file with the right permissions
- A user who can administer the machine On Ubuntu the sudo group grants running commands as root.
- A system account for a service -r picks a UID below 1000, -M skips the home directory, nologin blocks interactive login.
- A user with an SSH key instead of a password No password is set, so password login is closed while key login works — see ssh-keys.
- What ends up in the new home directory With -m the contents of /etc/skel are copied in:
- Add to a group and check that nothing was lost
- Remove from one group The same without gpasswd:
- A new group doesn't work in an open session A process gets its groups when it starts.
- Close login for a while -L closes only password login:
- Management A common mistake.
- Passwords, locking, su System users (daemons) usually have uid < 1000, nologin, no password (useradd -r).
Processes
- What is this process {#identify} Name, parent, user, full command, working directory, program file and service — enough to tell where the process came from.
- Find and recover a deleted but open file {#deleted} find prints links like /proc/956/fd/3:
- A service's environment {#service-env}
- Shell commands
- Surviving logout For services, use a systemd unit:
- Running in parallel For serious parallelism, use xargs -P N (see xargs) or GNU parallel.
- namespaces Types:
- cgroups (v2) CPUQuota=50% is half of one core; MemoryMax= is a hard ceiling:
- Slices and CPU sharing {#cpu-weight} systemd places processes in a tree of groups.
- Find the process that loads the disk {#find-io-hog} The general order for all resources is in system-monitoring.
- Lower a process's disk priority {#lower-io} nice lowers the CPU share, ionice the disk share; a backup on a busy server needs both.
- Watch one process {#watch-pid}
- End a process properly TERM lets the program close files and remove temporary ones.
- End by name pkill matches part of the name:
- A service — through systemctl systemd restarts a service killed with kill if it has Restart= — see systemctl.
- A process hangs in the terminal Ctrl+C sends INT, Ctrl+Z sends TSTP (stops it and returns the prompt).
- Load above the CPU count: who is queued {#who-is-running} Two R tasks at 48.8 % share one CPU.
- Find what D processes wait for {#find-d} Read the stack bottom up:
- Watch the load over time In vmstat, column r is tasks in R (running and waiting for a CPU), b is tasks waiting for the disk.
- Common tasks
- The FD column and locks {#fd-column} FD is the descriptor number, then the mode:
- Deleted files: +L1 and DEL {#deleted} A file that was deleted or replaced with a new one lives on while a process holds it — an open unlinked file.
- Add a swap file {#swap-file} To turn swap on at boot, add a line to /etc/fstab:
- Turn swap off {#swapoff} Then remove the line from /etc/fstab and delete the file.
- Drop the cache before a measurement {#drop-caches} This is only for experiments:
- Find whom OOM killed and when {#find} Match the time against the service's journal (journalctl -u <service>) to see what the service was doing before it died.
- A memory limit for a service {#memorymax} The limit goes into a drop-in, a file that extends the unit (see drop-in):
- Protect an important process {#protect} Only root can set a negative adjustment.
- Reproduce OOM safely {#reproduce} tail waits for a newline and keeps all input in memory until it hits the 64 MiB of its group.
- Check whether a program is running -x requires the whole name to match:
- Find the script, not the interpreter All Python scripts share the process name python3; they differ by command line.
- Look at the details of what you found -d, joins the PIDs with commas — the form ps -p accepts, see ps.
- List before pkill pkill takes the same selection options as pgrep but sends a signal — see kill.
- Viewing
- Signals Signal # Meaning TERM 15 graceful shutdown (the default), the process can clean up KILL 9 kill immediately, can't be caught (data may be lost) HUP 1 "hangup"…
- Priority and states {#priority} The STAT column in ps:
- What the STAT letters mean Letter State R running or waiting for a CPU S sleeping, waiting for an event D waiting on disk or network, signals can't interrupt T stopped (Ctrl+Z or a STOP…
- Find a process by name without grep itself ps aux | grep nginx also finds the line of grep nginx itself — hence the "extra" process in the output.
- Custom columns and the parent etime is how long the process has run, ppid is the parent's PID:
- A service's process tree
- Separate two observations {#two-observations} This provides a convenient pause between manual measurements.
- Start a short background task {#background-delay} Run the entire example in the same shell:
- Interrupt a manual delay {#interrupt-delay} Start sleep 30 in the foreground and press Ctrl+C.
- A program exits silently with code 1 {#silent-exit} -o writes the trace to a file, and the program's output stays on screen.
- Run as the service user {#as-service-user} root can read any file, so sudo strace shows no permission failures.
- Which files a program reads {#which-files}
- Where it connects {#network} The address and port are in the connect arguments.
- What a process is stuck on {#stuck} A single unfinished line means the process waits in that call:
- Summary: which calls and how many {#summary} calls is how many times, errors how many failed, % time the share of time in the kernel.
- Load that does not hurt the neighbours {#safe} With nice -n 19 the process takes all the free CPU (97.4 %) and yields it to any process with the normal nice value.
- Raise the load average {#raise-load} Three workers on one CPU push the load towards 3.
- Get an OOM in a cgroup {#memory-oom} systemd stopped the whole service at the very first OOM (OOMPolicy=stop).
- In the background, under control {#background} A shell job dies with the session.
- Who eats the CPU and memory ps takes a snapshot, and its %CPU is the average over the whole life of the process.
- A snapshot for a report One file with the time, load, memory and process list — attach it to a ticket or compare it with a similar snapshot later.
- Find what is loading the CPU Open top, press P (sort by CPU) and c (full command line).
- Find what ate the memory Press M to sort by %MEM.
- Stop a process right from top Press k, enter the PID (the top process is offered by default) and a signal:
- A snapshot for a report or ticket -b (batch) prints plain text without redrawing the screen; -n 1 takes one snapshot.
- htop htop is the same idea with color, mouse and scrolling.
- How many files are open and how many are allowed {#count-fds} A descriptor count close to the soft limit means the service will soon get Too many open files.
- Raise a limit in your shell {#raise-shell} This affects the shell and everything started from it.
- Who listens on a socket u_str is a stream socket (like TCP), u_dgr a datagram one (like UDP).
- Test a socket by hand curl sends an HTTP request into the socket; the name in the URL only goes into the Host header.
- Give nginx access This lasts until the application restarts:
- The PostgreSQL socket A directory in -h means a socket connection, the same as no -h at all.
- Save status before another command {#save-status} Run this in one shell:
- Distinguish suspension from termination {#termination-only} For your saved PID, use wait -f "$child_pid" when job control is enabled and termination is required.
- Keep launch and collection together {#same-parent} Start the task and wait for it in the same shell.
Services and systemd
- Checking
- A client of your own server {#client} iburst makes the first four polls back to back, so the sync takes seconds instead of minutes.
- A server for your machines {#server} On node2:
- Check the sync from a script {#check-script} waitsync <tries> <offset> waits until the clock is in sync and the correction is below the given one (0.5 s here), polling every 10 seconds.
- Correct the clock now {#step-now} makestep without a fresh measurement changes nothing:
- cron A crontab line has five time fields plus a command:
- Other users' crontabs {#user-crontabs} Personal crontabs live in /var/spool/cron/crontabs/, one file per user.
- Schedule and time zone {#timezone} cron reads the schedule in the machine's time zone:
- systemd timers A pair of files:
- Leases and diagnostics
- Provisioning (as code) Data sources, dashboards, and alerts are defined in files — reproducible, in git, not through clicking:
- Balancing and routing balance When roundrobin evenly, in turn (the default) leastconn the least-loaded server (long sessions, databases) source sticky by the client's IP Routing by…
- Three kinds of name systemd distinguishes three host names:
- Checking a service So the VIP moves when the application fails, not only when the whole node does:
- Managing VMs
- Networks and storage Snapshots:
- Who will answer a name The first command shows the answer as a client sees it, the second which listen and server_name nginx actually read, in file order.
- Find where the proxy breaks The error.log line names the upstream — where nginx went.
- Relaying through a smarthost The typical "the server sends notifications through an external SMTP" setup (main.cf):
- A role and a database for an application A new password — ALTER ROLE appuser PASSWORD '…';; list roles with \du in psql, databases with \l.
- A password without typing: ~/.pgpass {#pgpass} A line is host:port:database:role:password; * matches any value.
- Dump formats {#dump-formats} pg_dump takes a logical dump — the commands and data the database is rebuilt from.
- Restore into a new database {#restore-new-db} A new empty database has no conflicts:
- Compare a copy with the source {#verify-copy} The same row count, selection checksum and counter value in the source and the copy mean the data matches.
- PromQL and checking status The web UI is on :9090.
- redis-cli
- Server
- Client (Linux)
- Check whether a service is running
- Start, stop, and enable at boot
- See what the service has logged
- Control reload vs restart:
- Viewing and units edit creates a drop-in at /etc/systemd/system/<unit>.d/override.conf — the packaged unit is untouched, updates won't overwrite it.
- Targets A target is a group of units systemd brings the boot up to:
- Move a job from cron to a timer The service:
- Run the job now and check the result For oneshot, systemctl start waits for the script to finish and returns 0 or 1.
- An hour after the previous run
- A temporary timer without files Such a timer lasts until reboot; stop it with systemctl stop tick.timer.
- Try a script in the service environment The script runs as a temporary service:
- Commands
- Time zone {#timezone} The zone changes only how the time is shown:
- chrony instead of timesyncd {#chrony} Installing chrony removes systemd-timesyncd.
Network
- Commands
- A status code for checks The first command prints the code; 000 means there was no HTTP response.
- A site by name without DNS -H 'Host:
- HTTPS with your own CA --cacert adds a trusted root for one request.
- A request into a unix socket The connection goes to the socket file; the name localhost only goes into Host.
- Data and headers With -d curl picks POST itself; -X POST is optional.
- dig / host / nslookup
- Commands The interface name comes from ip -br l.
- Just the status code -o /dev/null throws the body away, -w prints the code.
- A site by name when DNS does not know it The first command changes only the Host header.
- A request by hand This shows HTTP is plain text:
- Who answered: nginx or the application An access.log line holds the client address, time, request line, code and response size:
- ip objects Object About Common ip address (a) IP addresses on interfaces ip -br a ip link (l) the interfaces themselves (up/down, MTU, MAC) ip -br l ip route (r) the…
- Commands Changes made with ip ...
- Address, prefix and subnet 192.0.2.10/24 is an address and a prefix:
- Network diagnostics The natural ladder:
- Checking ports Distinguish the responses:
- Data and transfer
- ping In the output, look at:
- traceroute / mtr mtr is the main tool:
- What the machine shows to the outside {#audit} A port that listens on 0.0.0.0 and shows as open from outside is part of the attack surface.
- Output for a script {#grepable} Each port is number/state/protocol//name///:
- Check one port {#one-port}
- Applying changes Over SSH on a remote machine, change network configuration with netplan try:
- Several files under /etc/netplan All the files are applied together, in name order (01-..., 50-...); a later file can override an earlier one's settings for the same interface.
- A permanent route to a network behind a neighbour {#static-route} A route added with ip route add lasts until a reboot.
- Tell "no path" from "no reply" Network is unreachable is printed at once:
- Destination Host Unreachable A host in your subnet didn't answer ARP — it's missing or off.
- A check in a script
- Inside the training network The training machine has no network except lo:
- Commands
- States and filters Filter by TCP state — state <name> (or state connected/listening):
- Generation Installing on the server:
- File permissions sshd enables StrictModes by default:
- ssh-agent The agent keeps the decrypted key in memory so you don't have to type the key's passphrase every time:
- Copying and tunnels
- Populate known_hosts for a new server -H hashes the hostname in the file — the same thing ssh itself does on a first connection (see ssh-client).
- Several hosts from a list Handy before rolling out a group of VMs, or in cloud-init/an Ansible playbook, when known_hosts is built in one step for a whole fleet.
- Verify a fetched key against a fingerprint
- Filters BPF syntax:
- Build a two-node network The ends' addresses come from one subnet; otherwise a route is needed (see ip).
- Find the other end of a pair
- Remove the training network A veth pair doesn't live alone:
- netplan: VLAN and bond
- Checking
- Commands
- Common tasks Paired with DNS:
- Investigating an attack A typical path for "where is this coming from" (combined with fail2ban/journalctl logs):
Storage and file systems
- A line for fstab
- Compare an fstab line with the device If it does not, fix fstab.
- Find a device by label or UUID
- What is on a disk with no filesystem
- Limits and reports
- xfs quotas xfs works differently — quotas are turned on with a mount option, not quotacheck:
- df / du / ncdu -x/-xdev is the key to a clean result:
- What to clean up
- Partition an empty disk in one command The partition starts at 1 MiB:
- Two partitions on one disk
- Add a partition in free space No mklabel here:
- The same in fdisk, step by step For the end you can type a size such as +10G instead of Enter.
- An MBR table for an older system On MBR the first word after mkpart is the partition type (primary), not a name.
- The kernel does not see the new partitions
- Creating and labeling Mounting via /etc/fstab is best done by UUID (/dev/sdX names can shift).
- Tuning and info (ext4)
- Checking (fsck) Never run fsck/xfs_repair on a mounted filesystem — it can corrupt data.
- A practice disk with a partition
- A filesystem image without partitions
- Clean up afterwards
- Attach an image at boot An /etc/fstab line with the loop option — mount attaches the file at boot.
- Find a new disk before partitioning it
- Mountpoints and UUIDs for fstab
- Custom columns for scripts
- Commands by layer Layer Create Show Extend PV pvcreate /dev/sdb pvs — VG vgcreate data /dev/sdb vgs vgextend data /dev/sdc LV lvcreate -L 10G -n vol1 data lvs lvextend -r -L +5G…
- Creating and extending
- Snapshots and moving data
- A new data partition
- Find a partition by its label
- Less root-only space on a big disk By default ext4 keeps 5% of the space for root only.
- Lots of small files The number of inodes is fixed at creation.
- A filesystem inside a file More in Loop device.
- Mounting Common -o options:
- Bind mounts and tmpfs
- A new disk in fstab: UUID and nofail {#nofail} nofail is for data disks.
- Server /etc/exports (one line per export):
- Client
- Overlays and conversion
- Snapshots (internal) For running VMs, take snapshots through virsh snapshot-* (see kvm-libvirt), not qemu-img against a live image.
- ext4: resize2fs
- xfs: xfs_growfs
- Both steps at once
- Creating an array
- Replacing a disk and growing the array
- Monitoring
Logs and audit
- Commands
- Your own lines in the journal: logger and -t {#logger} logger -t tag writes a line to the journal under that tag, and journalctl -t tag shows only those lines.
- Commands
- Centralization and rate limiting Receiver (central log server) — enable the input module:
Boot
- Change the default target {#set-default} The target changes at the next boot.
- Who starts a unit at boot {#who-wants}
- Boot into rescue or emergency {#boot-into-rescue} In the GRUB menu select an entry and press e.
- Fix things from emergency and boot on {#fix-from-emergency} mount -a without errors means fstab is fine, and systemctl default takes the boot to the default target.
- Debugging
- Kernel errors of this boot {#errors-this-boot}
- Follow the messages {#follow} -w first prints the whole buffer — hundreds of boot lines — and then waits.
- A crashed program: segfault {#segfault} The program touched memory that is not its own.
- An ext4 filesystem error {#ext4-error} ext4 found damage:
- OOM: a process ended for lack of memory {#oom} The lines Out of memory:
- A task hung in D {#hung-task} The process stayed in state D longer than kernel.hung_task_timeout_secs (120 seconds on Ubuntu; here the threshold was lowered to 20).
- Commands
- Autoload and blacklist
- dmesg / kernel messages This is where driver and hardware problems show up.
- Find a parameter {#find} 2>/dev/null hides the permission denied on key lines; with sudo all parameters are visible.
- Check that a value survives a reboot {#check-persistent} If sysctl --system gives the right value, boot will give the same:
- Who set the value {#who-set} sysctl --system first prints all the * Applying … lines in order, then all the values.
- Return the default value {#revert} Remove your file from /etc/sysctl.d/ and set the value by hand (sudo sysctl -w vm.swappiness=60) or reboot — sysctl --system does not restore old values, it…
- GRUB The config is /etc/default/grub (don't edit the generated grub.cfg directly):
- Targets and timing Target What it is multi-user.target a server with no graphics (normal) graphical.target + GUI rescue.target single-user, root mounted, minimal services…
- Find what delays the boot {#slow-boot} systemd-analyze — how long the boot took and to which target.
- Check a unit before starting it {#check-unit} The last line suits a script:
- Did the service come up at boot by itself {#started-at-boot} ActiveEnterTimestampMonotonic is the microseconds from the kernel start to the moment the service became active:
- Check the version and origin
- Parameters the kernel booted with
- Kernel messages at boot and at runtime
Packages
Security
- Modes and commands {#modes} Profiles live in /etc/apparmor.d/.
- Profiles and rollout A profile's structure (simplified):
- Rules: watch and syscall
- Searching events
- Reading an event {#event} On the lab machine the auditd service is off:
- Permanent rules: rules.d {#rules-d} augenrules builds /etc/audit/audit.rules from all the rules.d/*.rules files and loads it into the kernel; auditd does the same at start.
- A port below 1024 without root {#low-port} A service gets the part through its unit; a program outside systemd gets it through its file:
- Find files with capabilities {#find} A clean machine shows the three files from the block above.
- Which parts a service has {#service-caps}
- Management
- ufw
- A persistent nftables set {#nftables-persistent} Rules added with nft add live until a reboot.
- Encryption and signing
- Password policy {#password-policy} Test it by action:
- Lockout after three failures {#lockout} The file is replaced whole — compare its old stack with this one (grep -v '^#' /etc/pam.d/common-auth | grep .) and carry over any lines missing here.
- Edit PAM without locking yourself out {#safe-edit} Open a second terminal with sudo -i and keep it until the check is done.
- Restrict a service with a drop-in {#drop-in} Check every setting by the service's work:
- Try a setting on one command {#systemd-run} systemd-run runs a command as a temporary service with the same settings:
- Hardening Parameter Why PermitRootLogin no don't allow root to log in directly PasswordAuthentication no keys only (the main defense against brute force) MaxAuthTries 3…
- Commands
- Reading and rules iptables rules don't persist on their own.
- What the server sends {#server-certificate} The first certificate in the output is the site certificate.
- Check a chain locally The first command, without the intermediate, says error 20 at 0 depth lookup:
- Build a full chain file {#fullchain} The order is the site certificate first, the intermediate after it.
- Do the key and certificate match? Equal sums mean a pair.
- Issue a certificate with the old key {#renew-same-key} -copy_extensions copy carries SAN from the request into the certificate.
- How long until it expires -checkend N asks whether the certificate expires within N seconds (2592000 is 30 days):
- Trust your own CA system-wide {#trust-own-ca} The file must be named *.crt.
- Let's Encrypt (certbot) A public CA for sites on the internet:
- Is it on and when does it run {#check} Both values "1" and both timers enabled mean updates run once a day.
- Hold a package back {#blacklist} The names are regular expressions:
- Find services running old files {#find-stale}
- Grant one command in a separate file A separate file is easy to see and easy to remove, and the main /etc/sudoers stays untouched.
- Check a rule before installing it Check the grammar first, then the meaning:
- Check as the person the rule is for -n forbids the password prompt:
Automation
- Check a playbook before running it {#before-run} On a correct playbook --syntax-check prints only playbook:
- To another machine over SSH {#remote} The inventory node2.ini:
- Part of a playbook {#partial} With -t page the fact gathering, the tagged task and its handler ran — ok=3 changed=2.
- A variable from the command line {#extra-vars} -e site_title=Changed overrides the playbook's vars::
- Inventory {#inventory} What Where Means machine name node2 how the machine is named in the output; Ansible also connects by it if there is no ansible_host ansible_host the machine's…
- One-off commands {#adhoc} ansible <machines> -m <module> -a '<arguments>' runs one module on all machines of a group.
- become: through sudo {#become} Modules run as the user Ansible logged in as.
- Playbooks and roles Variables go in group_vars/, host_vars/; secrets in ansible-vault (ansible-vault encrypt secrets.yml, run with --ask-vault-pass).
Containers
- Which image a container runs The first inspect field is the name the container was created with, the second is the image ID.
- Check a digest by hand index.json points to the manifest by digest, the manifest file is named with that digest, and sha256sum of it gives the same number.
- Move an image to a host without network
- Image list for a script
- Free up space
- Validate the file before starting
- Stack state for a script --format json prints one JSON object per line for each container — jq parses them one by one.
- Stop one service
- Logs of all services at once Each line starts with the service name.
- Why the container stopped Code 0 means the command simply finished:
- Re-create a container with new options Data in the volume survives re-creation; data in the container layer does not.
- Find a container among host processes
- A command in a container from a script docker exec -it needs a terminal.
- A site on nginx:alpine CMD is inherited from the base:
- A process that is not root adduser -D is the busybox version:
- Check the image before running the service
- Rebuild and swap the container A new image does not reach a running container by itself — the container has to be re-created.
Nothing found. Try a shorter query.