tips
261 tips Linux
One command, setting or habit at a time about Linux: what it does, the line to copy and a caveat or two.
Network and DNS 37
-
Prints the forwarding table of a Linux bridge, so you can see where a MAC address lives.
bridge fdb show br br0 -
Log each missing reply with a timestamp, so short outages become visible.
ping -O -D 192.0.2.1 -
Try a smaller or larger MTU on one interface without editing any network config.
ip link set dev eth0 mtu 1400 -
Make a fast link behave like a slow or lossy one to see how your app copes.
tc qdisc add dev eth0 root netem delay 100ms -
Find which process listens on a local socket file, like the Docker or database socket.
ss -xlp -
Make the port light blink so you know which physical socket belongs to eth1.
ethtool -p eth1 10 -
Run a command with its own interfaces and routes, apart from the rest of the system.
ip netns add test1 -
Shorten the wait when the first name server in resolv.conf is down.
options timeout:2 attempts:2 rotate -
Read the card's own statistics to spot CRC errors, missed packets and other link trouble.
ethtool -S eth0 | grep -iE 'err|drop|miss|crc' -
See whether a connection is waiting on keepalive, retransmits or a closing timer.
ss -tno state established -
Trace the route to a web server with packets that a firewall lets through.
traceroute -T -p 443 -n example.com -
Find out which driver and firmware a network card uses before you search for a bug.
ethtool -i eth0 -
Route a single network via a different router without touching your config files.
ip route add 198.51.100.0/24 via 192.0.2.1 -
Expose a service on another port or address for a quick test, no proxy config needed.
socat TCP-LISTEN:8080,fork,reuseaddr TCP:127.0.0.1:3000 -
Make programs try the IPv4 address first when a host has both.
precedence ::ffff:0:0/96 100 -
Prints totals of open sockets per protocol and TCP state in a few lines.
ss -s -
Records packets to a file with a filter and a packet limit for later analysis.
sudo tcpdump -i any -n -c 500 -w /tmp/capture.pcap host 192.168.1.50 and port 443 -
Shows the order in which Linux asks /etc/hosts, DNS and other sources for a name.
grep ^hosts /etc/nsswitch.conf -
Prints resolvectl lookup results without headers, so scripts get only the answers.
resolvectl query -4 --legend=no example.com -
Makes NetworkManager use a random or per-network MAC address for a Wi-Fi connection.
nmcli connection modify "Cafe Wifi" 802-11-wireless.cloned-mac-address random -
Streams link, address and route changes live, so short network hiccups leave a trace.
ip -ts monitor label link address route -
Shows per-interface error and drop counters so you can spot a bad cable or port.
ip -s -s link show eth0 -
Shows round trip time, MTU and congestion window for each TCP connection to a host.
ss -tin dst 192.168.1.30 -
Checks whether another device on your LAN already answers to an IP address.
sudo arping -D -I eth0 -c 3 192.168.1.50 -
Adds an extra IP address to an interface right away, and the address disappears again after a reboot.
sudo ip addr add 192.0.2.10/24 dev eth0 -
Sends pings with the don't-fragment flag set, so you can find the largest packet that passes.
ping -M do -s 1472 -c 3 example.com -
Shows the negotiated speed, duplex mode and link status of a network interface.
sudo ethtool eth0 -
Asks the kernel which gateway, interface and source address it would pick for a destination, without sending anything.
ip route get 1.1.1.1 -
Traces the route to a host like traceroute and reports the path MTU, as a normal user.
tracepath -n example.com -
Prints one line per network interface with its state and IP addresses.
ip -br address -
Shows which program is using which network port, useful when a port is already taken.
-
Makes a Linux machine use the subnet routes that other tailnet devices advertise.
sudo tailscale set --accept-routes -
Shows the address a normal program gets, including hosts file entries that dig ignores.
getent hosts nas.local -
Empties the local DNS cache of systemd-resolved without restarting the service.
resolvectl flush-caches -
Resolves a name through systemd-resolved and shows which link, protocol and cache gave the answer.
resolvectl query example.com -
Captures a few DNS packets from the command line and prints them.
sudo tcpdump -ni any port 53 -c 20 -
Lists only the TCP connections in a chosen state that match a port, instead of every socket.
ss -tn state established '( dport = :443 )'
Linux and shell 30
-
Adds a last line with how many lines are only in file one, only in file two, and in both.
comm --total a.txt b.txt -
Reverses a patch, so the files go back to how they were before it was applied.
patch -R g.txt < f.patch -
Reproduce the 'works in my shell, fails in cron' problem on purpose.
env -i ./backup.sh -
Stop a pipeline from holding back output until a buffer of several kilobytes is full.
tail -f access.log | cut -d' ' -f1 | uniq -
Create a symlink with a relative path without counting the dots yourself.
ln -sr /srv/site/shared/uploads /srv/site/current/uploads -
Wait for a file, a service or a disk to change without writing a loop.
watch -g -n 5 ls /srv/inbox && echo 'new file in the inbox' -
Free the space of a runaway log without deleting the file or restarting the program.
truncate -s 0 /var/log/app/debug.log -
Copy a big folder in seconds as hard links, as a quick snapshot before you change things.
cp -al photos photos-before-cleanup -
Resolves a chain of symlinks and prints the real absolute path of the target.
readlink -f /usr/bin/python3 -
Copies files into a target folder while keeping the directory path they came from.
mkdir -p ~/config-export -
Clones a big file in an instant on filesystems that support copy on write.
cp --reflink=always vdisk1.img vdisk1-before-update.img -
Copies or moves files without overwriting existing ones, with an exit status you can predict.
cp -r --update=none /mnt/user/photos/import/* /mnt/user/photos/library/ -
Shows when a file was last changed, formatted the way your script needs it.
mv app.log "app-$(date -r app.log +%F).log" -
Replaces a symlink that points to a directory, rather than adding a link inside that directory.
ln -sf /srv/app/releases/v2 /srv/app/current -
Prints a number sequence with leading zeros, so numbered names line up and sort correctly.
for i in $(seq -w 1 "$n"); do -
Gives a file the same modification time as another file, or any date you choose.
touch -r notes.orig.md notes.md -
Shows progress, speed and time left for data going through a pipe.
pv backup.tar.gz | tar xz -
Turns a messy path with dots and symlinks into a clean absolute path, or one relative to a folder.
realpath ../../data/./file.txt -
Compares two files byte by byte and reports where they first differ, or all differing bytes with -l.
cmp -l file1.bin file2.bin | head -
Converts plain numbers into human-readable sizes, and works on any number that you pipe into it.
echo 1610612736 | numfmt --to=iec -
Compares two files and prints only the changes, with a few lines of context, in the format patch tools expect.
diff -u nginx.conf.bak nginx.conf -
Blocks until something happens to a file or folder, so a script can react without polling.
inotifywait -m -e close_write /srv/inbox -
Splits a large file into fixed-size parts with numbered names, which cat can join back together.
split -b 1G -d --additional-suffix=.part big.iso big.iso. -
Turns plain-English dates such as yesterday or next friday into a real date on the command line.
date -d '2 days ago' +%F -
Stops processes by exact name, so killing 'vim' does not also take down 'gvim' or 'vimdiff'.
pkill -x node -
Prints the lines of a file in reverse order, which puts the newest log entry on top.
tac /var/log/app.log | head -n 20 -
Draws the files and folders of a directory as a tree, cut off at the depth you choose.
tree -L 2 -
Adds a column with the filesystem type, so you see what is on each mounted disk.
df -hT -
Prints CPU, memory, swap and I/O wait figures once per second.
vmstat 1 5 -
Runs a heavy command with the lowest CPU and disk priority.
nice -n 19 ionice -c3 tar -czf /backup/www.tar.gz /var/www
Text processing 28
-
Compare two lists without sorting them first, line for line and exact.
grep -vxFf allowed.txt users.txt -
Check how wide a file is before you print it, wrap it or set a column width.
wc -L access.log -
Find the stray carriage return, tab or odd byte that breaks a script or config.
head -n 3 config.env | od -c -
Find the entries that appear twice in a list, or the ones that appear once.
sort hosts.txt | uniq -d -
Remove a single field from a CSV or log without listing every field you want to keep.
cut -d, -f2 --complement people.csv -
Replace the first occurrence in a file and leave every later one alone.
sed '0,/^port=/s//port=8081 #/' app.conf -
Pull one section out of a config or log, from a start line to an end line.
sed -n '/BEGIN backup/,/END backup/p' /var/log/app.log -
Remove duplicates based on one column, like keeping one line per host name.
sort -u -k1,1 logins.txt -
Take the last part of a path or line when the number of fields changes.
echo /srv/media/films/2024/clip.mkv | rev | cut -d/ -f1 | rev -
Fix the garbled characters in an old export by converting its encoding.
iconv -f latin1 -t utf-8 old.csv > new.csv -
Split a long log or dump into separate files at every line that starts a new section.
csplit -s -z -f part- dump.sql '/^CREATE TABLE/' '{*}' -
Reflow ragged lines in notes, commit messages or a README to one width.
fmt -w 72 notes.txt -
Cut off a footer or trailing lines without counting how long the file is.
head -n -5 report.txt -
Find the config files where a setting is missing, not the ones where it is set.
grep -L 'Restart=' /etc/systemd/system/*.service -
Shows a few lines before and after every match, so you see what led up to an error.
grep -n -C 3 'segfault' /var/log/syslog -
Makes grep quit after the first match, or after any number you choose.
grep -n -m 1 'Out of memory' /var/log/syslog -
Prints only the matched text, like IP addresses, instead of the whole log line.
grep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}' /var/log/auth.log -
Only matches your search term as a whole word, not inside longer words.
grep -w port /etc/ssh/sshd_config -
Converts tab characters into spaces, so YAML files with tab indentation load again.
expand -t 2 compose.yaml > compose.fixed.yaml -
Combines lines from two text files that share the same value in a key column.
join <(sort hosts.txt) <(sort roles.txt) -
Sorts lines on one chosen column, as text or as numbers, instead of on the whole line.
sort -t, -k3,3n people.csv -
Sorts a file and writes the result back into the same file without emptying it first.
sort -o list.txt list.txt -
Sorts version numbers like 1.9 and 1.10 in the order a person would expect.
printf '%s\n' 1.10.0 1.9.2 1.2.0 | sort -V -
Removes the hidden carriage returns that make Windows text files misbehave on Linux.
cat -E script.sh | head -
Prints just the line count of a file, so you can use it directly in a script.
wc -l < access.log -
Wraps long lines to a chosen width and breaks them at spaces instead of in the middle of words.
echo "a very long sentence that keeps going and going" | fold -s -w 20 -
Lets grep use Perl-style patterns such as lookahead and \d, which the basic and extended syntax lack.
echo 'price=42 EUR' | grep -oP '\d+(?= EUR)' -
Adds line numbers to the output of a file or command, numbering empty lines as well.
nl -ba -w 4 -s ': ' /etc/hosts
Kernel and system 22
-
Sets a priority per swap area, so a fast one is used before a slow one.
sudo swapon -p 10 /swap-fast -
Controls how strongly the kernel reclaims directory and inode caches, with 100 as the default.
sysctl vm.vfs_cache_pressure -
See system wide open file usage next to its maximum in one line.
cat /proc/sys/fs/file-nr -
Have a remote server restart on its own instead of hanging forever after a panic.
sysctl kernel.panic -
Understand why a program got memory it could not use, and when to change the policy.
sysctl vm.overcommit_memory -
See which I/O scheduler a disk uses and try another one without a reboot.
cat /sys/block/sda/queue/scheduler -
Decode the taint number to see which loaded module or event marked the kernel.
cat /proc/sys/kernel/tainted -
Raise the inotify watch limit when an editor, sync tool or dev server cannot watch your files.
cat /proc/sys/fs/inotify/max_user_watches -
Starts a command on chosen CPU cores or changes the cores of a running process.
taskset -c 0,1 ffmpeg -i in.mkv out.mp4 -
Lists zram devices and sets up compressed swap in memory.
zramctl -
Shows the share of time tasks stall on CPU, memory or disk, over 10, 60 and 300 seconds.
cat /proc/pressure/cpu -
Sets how eagerly linux swaps out memory compared with dropping page cache.
sysctl vm.swappiness -
Sets English system messages with Dutch-style 24-hour date and time formatting.
sudo localectl set-locale LANG=en_US.UTF-8 LC_TIME=nl_NL.UTF-8 -
Lists PCI devices together with the kernel driver in use and the modules that could drive them.
lspci -k -
Queries the user database through the Name Service Switch, so it also finds users from LDAP or other sources.
getent passwd jordi -
Lists the USB devices the kernel sees, with the -t option showing how hubs and devices connect.
lsusb -t -
Shows the system uptime as readable text, such as weeks, days and hours, instead of the classic load line.
uptime -p -
Sets the system time zone with a name from the official list.
sudo timedatectl set-timezone Europe/Amsterdam -
Changes the hostname of a systemd machine at once and keeps it after a reboot.
sudo hostnamectl set-hostname nas01 -
Summarizes the CPU model, core and thread counts and virtualization flags.
lscpu | grep -E 'Model name|Socket|Core|Thread|Virtualization' -
Shows only kernel errors and warnings instead of the whole ring buffer.
sudo dmesg --level=err,warn -
Changes a kernel setting at once and keeps it across reboots with one small file.
sudo sysctl -w vm.swappiness=10
Access and security 15
-
List accounts that have not logged in for a number of days
lastlog --before 90 -
Rehearses a Let's Encrypt renewal against the staging server without saving any certificate.
certbot renew --dry-run -
Shows each certificate Certbot manages, with its domains, expiry date and file paths.
certbot certificates -
Edit system files safely without running a whole editor as root.
sudoedit /etc/ssh/sshd_config -
Run a command as a service account from a root script, without su or sudo prompts.
runuser -u www-data -- php /var/www/app/occ status -
Shows the password and account expiry settings of a Linux user.
chage -l <user> -
Clears sudo's cached password so the next command asks for it again.
sudo -k -
Shows the failed logins of a user and clears the records that lock the account.
sudo faillock --user alice -
Checks sudoers and its included files for syntax errors and returns an exit code.
sudo visudo -c && echo sudoers ok -
Keeps fail2ban from banning addresses on your own LAN or tailnet.
ignoreip = 127.0.0.1/8 ::1 192.168.1.0/24 100.64.0.0/10 -
Prints every table, chain and rule that nftables currently has loaded in the kernel.
sudo nft list ruleset -
Disables a user's password login on Linux, and what else is needed to really block the account.
sudo passwd -l olduser -
Lists the password aging and expiry details of a user account.
chage -l jordi -
Verifies that a downloaded file matches its detached signature and was signed by the key you expect.
gpg --import project-signing-key.asc -
Shows the log of bad login attempts that Linux keeps in /var/log/btmp.
sudo lastb | head -n 20
Backup repositories 11
-
Previews which restic snapshots a retention policy would delete without removing anything.
restic -r /srv/restic-repo forget --keep-daily 5 --dry-run -
Mounts a restic repository through FUSE so you can browse and copy files from every snapshot.
restic -r /srv/restic-repo mount /mnt/restic -
Restores a single file or folder from a restic snapshot into a directory of your choice.
restic -r /srv/restic-repo restore latest --target /tmp/restore --include /mnt/user/appdata/<app>/config.xml -
Writes a file or folder from a restic snapshot to stdout, ready for a pipe or redirect.
restic -r /srv/restic-repo dump latest /mnt/user/appdata/<app>/config.xml > config.xml -
Copies snapshots from one restic repository into another, for example to keep an offsite second copy.
restic -r /srv/restic-repo-copy copy --from-repo /srv/restic-repo -
Frees the repository space that borg prune only marks as unused.
borg compact /path/to/repo -
Previews which borg archives a prune rule keeps and removes, without changing the repository.
borg prune -v --list --dry-run --keep-daily=7 --keep-weekly=4 /path/to/repo -
Verifies the stored data of your Borg archives instead of only their structure.
borg check --verify-data /path/to/repo -
Lists only the added, modified and unreadable files in a Borg backup run.
borg create --list --filter=AME /path/to/repo::{hostname}-{now} ~/Documents -
Lists files added, removed and changed between two archives in a Borg repository.
borg diff /path/to/repo::archive1 archive2 -
Runs a Borg repository check in time-limited pieces that resume where the last one stopped.
borg check --repository-only --max-duration=3600 /path/to/repo
Identify and inspect 11
-
Shows the settings stored in an ext4 filesystem, such as features, state and block size, in one short screen.
sudo dumpe2fs -h /dev/sdb1 -
Asks the drive itself for detailed identification and feature data, not the kernel's boot-time copy.
sudo hdparm -I /dev/sda -
Lists power devices and prints detailed battery information from the command line.
upower -i /org/freedesktop/UPower/devices/battery_BAT0 -
Shows buses, bridges and devices as a tree, so you see what hangs off what.
lspci -t -
Let a script check which distribution and release it runs on, without parsing text.
. /etc/os-release -
Find out why a program will not start with 'error while loading shared libraries'.
ldd /usr/local/bin/tool -
Lists the shared libraries registered in the linker cache so you can search them.
ldconfig -p | grep libssl -
Lists file locks held on the system with the process that owns each one.
lslocks -
Prints a map of the GPIO header with physical pins, GPIO numbers and functions.
pinout -
Finds the processes that use a mount or a port, so you know what blocks an unmount.
sudo fuser -vm /mnt/backup -
Lists the memory slots, module sizes and speeds of a machine from the firmware tables.
sudo dmidecode -t memory
Logs and diagnostics 9
-
See which programs crashed, when, and with which signal, all from the journal.
coredumpctl list --since today -
See the reboots and shutdowns of a machine, so you can tell a crash from a planned restart.
last -x shutdown reboot | head -
Show every new journal line on a spare virtual terminal of the machine.
sudo mkdir -p /etc/systemd/journald.conf.d -
Rotate the log of a program that keeps its log file open and can't reopen it.
rotate 4 -
Name rotated log files after their date, so you find the right day at once.
rotate 14 -
Test a logrotate config and see what it would rotate, without changing any log.
sudo logrotate -d /etc/logrotate.d/myapp -
Rotate a log on its normal schedule and also as soon as it passes a size.
maxsize 100M -
Explains and changes the per-service limit that makes journald drop messages in a burst.
[Journal] -
Sets how often journald syncs its files to disk, which decides how much a crash can lose.
[Journal]
Mounts and writes 9
-
Watches the mount table and prints each mount, umount, remount or move as it happens.
findmnt --poll -
Marks an fstab mount as optional, so a missing disk no longer holds up the boot.
UUID=1234-abcd /mnt/backup ext4 defaults,nofail,x-systemd.device-timeout=5s 0 2 -
Know when a copy has really reached the disk before you pull a USB drive.
watch -n 1 "grep -E '^(Dirty|Writeback):' /proc/meminfo" -
Create a fast scratch folder in memory with a hard size cap.
mount -t tmpfs -o size=512M,mode=1777 tmpfs /mnt/scratch -
Returns success only when a folder is a mount point, so scripts can check first.
if ! mountpoint -q /mnt/backup; then -
Shows the same folder at a second path, which works where a symlink does not.
sudo mount --bind /mnt/data/media /srv/media -
Stops the filesystem from updating access times on every read, which saves writes on data disks.
sudo mount -o remount,noatime /mnt/data -
Gives a Linux machine swap space from a plain file, without changing any partitions.
sudo mkswap /swapfile -
Frees the mount point of a hung network share so the machine can shut down cleanly.
sudo umount -l /mnt/nas
Load and performance 8
-
Lower the priority of a job that is already running, without restarting it.
renice -n 10 -p 4242 -
Records system and process statistics to a file and lets you step through them afterwards.
atop -w /tmp/atop.raw 60 30 -
Give a background job the idle scheduling class, lower than even nice 19.
chrt -i 0 ./reindex.sh -
Find what makes the load average high while the CPU looks idle.
ps -eo stat,pid,wchan:32,cmd | awk '$1 ~ /^D/' -
Print one line per CPU core every few seconds to spot a single busy core, I/O wait or steal time.
mpstat -P ALL 2 5 -
Starts a command and reports its CPU, memory and disk use every second until it ends.
pidstat -u -r -d 1 -e tar czf /tmp/test.tar.gz ~/Documents -
Limits how fast rsync transfers data, so other traffic keeps working.
rsync -a --bwlimit=20M /srv/data/ backup:/srv/data/ -
Gives the load average and the CPU count so you can judge whether the load is high.
uptime
Hardening 6
-
Make sure a program cannot be fooled into writing to a file another user planted in /tmp.
sysctl fs.protected_regular fs.protected_fifos fs.protected_symlinks fs.protected_hardlinks -
Overwrites a file before deleting it, plus the manual's warning about copies and file systems.
shred -v -u -z ~/Documents/old-secret.txt -
Shows whether UEFI Secure Boot is switched on for the running system.
mokutil --sb-state -
Lists the loaded AppArmor profiles, their modes and how many running processes are confined.
sudo aa-status -
Sets an account shell to nologin so that service users refuse interactive logins.
sudo usermod -s /usr/sbin/nologin svc-backup -
Scans a folder recursively with ClamAV and lists only the infected files.
clamscan -r -i /mnt/user/share
systemd 6
-
See the NTP server, offset and poll interval of systemd-timesyncd
timedatectl timesync-status -
Reloads a service when it supports reloading and does a full restart when it does not.
sudo systemctl reload-or-restart nginx.service -
Sends a chosen signal to the main or all processes of a unit without looking up a PID.
sudo systemctl kill --signal=SIGHUP --kill-whom=main nginx.service -
Makes a Linux machine boot to a text login without starting the desktop.
systemctl get-default -
Removes files older than a set age from a directory every day, without cron.
d /srv/scratch 0755 root root 14d -
Prints the local time, the time zone and whether the clock is synchronised with an NTP server.
timedatectl
Boots and kernel 5
-
Hides the GRUB menu behind a short timeout, and the menu still appears when you press ESC or hold Shift.
GRUB_TIMEOUT_STYLE=hidden -
Lists the files in an initramfs image, so you can check a driver is in it.
lsinitramfs /boot/initrd.img-$(uname -r) -
Check whether a kernel option you added to GRUB actually reached the kernel.
cat /proc/cmdline -
Reports whether the bootloader in the Pi's EEPROM has a newer version available.
vcgencmd bootloader_version -
Shows the boot settings stored in the Pi's bootloader EEPROM before you change them.
rpi-eeprom-config
SSH 5
-
Makes ssh add your private key to the agent the first time it is used.
AddKeysToAgent yes -
Shows the four PermitRootLogin values and how to see the one your server really uses.
PermitRootLogin no -
Lets ssh add the key of a new server without asking, but still refuses a server whose key changed.
ssh -o StrictHostKeyChecking=accept-new [email protected] uptime -
Prints the server host key fingerprint as ASCII art so you can compare it by shape.
ssh -o VisualHostKey=yes [email protected] -
Lets a trusted SSH server hand you its additional host keys so known_hosts stays current.
Host *
Shell basics 5
-
Get one sanity check before a large or recursive delete, without the endless prompts of rm -i.
rm -I *.log -
Test from a script whether a PID still exists before you wait for it or start a new copy.
if kill -0 "$pid" 2>/dev/null; then -
Pauses a command that blocks your terminal and lets it continue in the background.
Ctrl-Z # pause the running command -
Switches back to the directory you were in before the last cd.
cd /var/log/nginx -
Reruns your previous command with sudo in front, so you do not retype it.
sudo !!
Disk usage 4
-
Hide the hundreds of small folders and see only the ones worth cleaning up.
du -h -t 1G /srv | sort -h -
Prints only the columns of df that you list, such as mount point, percentage and inode use.
df -h --output=source,fstype,size,used,avail,pcent,target -
Counts files per directory instead of bytes, to find what exhausts the inodes.
sudo du --inodes -x -d2 /var | sort -n | tail -
Adds the date of the latest change to each folder in a du listing.
du -h -d1 --time --time-style=long-iso ~/Downloads | sort -h
Inspecting packages 4
-
Saves the installed package list so another machine can install the same set.
dpkg --get-selections > packages.txt -
Compares two Debian version strings and answers with the exit code.
dpkg --compare-versions 1.10 gt 1.9 && echo newer -
Checks installed package files against the md5sums dpkg stored at install time.
dpkg --verify openssh-server -
Prints chosen fields of installed packages, such as name and version, in a format scripts can read.
dpkg-query -W -f='${Package}\t${Version}\n' 'openssh-*'
Processes and limits 4
-
Raise the open files limit of a running service without restarting it.
prlimit --pid 1234 --nofile -
Protect an important process, or offer up a less important one, when memory runs out.
choom -p 1234 -
Raises the open files limit for one shell session, up to the hard limit.
ulimit -Sn -
Prints the variables a running process was started with, one per line.
tr '\0' '\n' < /proc/$(pgrep -o nginx)/environ | sort
Array and disks 3
-
Lists the commands that show which process keeps a disk busy so the array cannot stop.
tail -f /var/log/syslog -
Shows on which array disk a file from a user share physically sits.
ls -l /mnt/disk*/Media/film.mkv 2>/dev/null -
Shows which process is listening on a given port, with its PID and owner.
sudo lsof -nP -i :53
Files and media 3
-
Lists and removes metadata from documents, images and other files, writing a cleaned copy.
mat2 --show report.pdf -
Measures ratio and speed of each zstd level on your data, so you can pick one.
zstd -b1 -e19 app-backup.tar -
Preallocates disk space for a file of the size you ask, without writing all the data like dd would.
fallocate -l 1G test.img
Storage 3
-
Makes journald drop messages above a chosen level before they are stored, such as debug.
[Journal] -
Caps the size of the in-memory journal, which matters on small machines such as a Raspberry Pi.
[Journal] -
Tells journald to keep a minimum of disk space free, as a floor next to the size cap.
[Journal]
Upgrading 3
-
Check after updates whether a reboot is needed, and which packages asked for it.
ls /var/run/reboot-required && cat /var/run/reboot-required.pkgs -
Lists services that still use outdated libraries after package upgrades.
sudo apt install needrestart -
Finishes the setup of packages left half installed after an interrupted apt run.
E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.
Containers 2
-
Raises the size of /dev/shm inside a container, for programs that need more shared memory.
docker run -d --shm-size=1g <image> -
Lists namespaces and the processes in them, which shows how containers are separated.
sudo lsns -t net
DNS and Pi-hole 2
-
Validates a BIND zone file the way the name server would, before you reload it.
named-checkzone example.com /etc/bind/db.example.com -
Prints the resource limits that apply to one running process.
cat /proc/$pid/limits
Debugging and speed 2
-
Get a summary table of syscalls, errors and time instead of thousands of trace lines.
strace -c -f ./slow-script.sh -
Reports elapsed time and peak memory of one command with GNU time.
/usr/bin/time -f "%e s elapsed, %M KB peak memory" tar czf /tmp/test.tar.gz ~/Documents
Services and logs 2
-
Lists every service that failed to start, so you know after a reboot if everything came back.
systemctl --failed -
Shows only the errors in the system log since the last boot.
journalctl -p err -b
Unit files 2
-
Removes drop-ins and overrides of a unit so it goes back to the vendor version.
sudo systemctl revert example.service -
Makes a service start only once the network is really up, not just started.
After=network-online.target
Automatic updates 1
-
Installs the updates during shutdown instead of in the background.
Unattended-Upgrade::InstallOnShutdown "true";
Clipboard 1
-
Copy command output to the desktop clipboard and paste it back from the terminal.
cat config.yml | xsel -ib
Config and keys 1
-
Makes sudo ll and other aliases after sudo work instead of giving command not found.
alias sudo='sudo '
Config constants 1
-
Records every file a program tries to open, including the ones that do not exist.
strace -f -e trace=openat -o /tmp/open.txt myprogram --serve
HTTP and nginx 1
-
Check whether an Apache module is enabled, and get a clean exit code for scripts.
a2query -m rewrite
Maintenance 1
-
Checks an ext4 filesystem for errors and only reports them, without repairing anything.
sudo e2fsck -fn /dev/sdb1
Modes and ownership 1
-
Gives a file to a user and that user's own group in one short command.
sudo chown alice: report.pdf
Nginx Proxy Manager 1
-
Runs Nginx Proxy Manager as a regular user instead of root and fixes folder ownership.
environment:
Permissions 1
-
Makes a FAT-formatted USB drive writable for your own user with mount options.
sudo mount -o uid=1000,gid=1000,fmask=0133,dmask=0022 /dev/sdb1 /mnt/usb
Quick checks 1
-
Shows live traffic per connection on an interface, with numeric hosts and ports.
sudo iftop -n -P -i eth0
Recording and logging 1
-
Writes a tagged message from a script to the system log so you can find it later.
logger -t backup "nightly sync finished"
Scripting 1
-
Give a graphical program a virtual display on a headless machine.
xvfb-run -a your-program --some-flag
Storage and updates 1
-
Deletes Flatpak runtimes that no installed app uses anymore.
flatpak uninstall --unused
System 1
-
Explains the script on the flash drive that runs your own commands each time Unraid starts.
cp /boot/config/go /boot/config/go.bak
Tailscale commands 1
-
Enables IP forwarding for a Linux subnet router and shows how to advertise the routes.
echo 'net.ipv4.ip_forward = 1' | sudo tee -a /etc/sysctl.d/99-tailscale.conf
Updates and backups 1
-
Exports the Borg encryption key to a file or paper, so a lost server doesn't lock you out.
borg key export /path/to/repo encrypted-key-backup
Windows 1
-
Lists the installed WSL distributions with their state and whether they run on WSL 1 or WSL 2.
wsl --list --verbose
More tips 2
-
Draws the running processes as a tree, so you see parents, children and their PIDs.
pstree -p -
Shows how much memory programs can still use, including cache that Linux gives back when asked.
free -h
Nothing in this filter yet.