Skip to content
All quick references

Linux & Bash

29 snippets · 10 sections

Day-to-day Linux administration - files and permissions, text processing, systemd, networking, storage, and the bash scripting patterns worth memorising.

01

Files & Navigation

Moving around

pwd                     # where am I
cd -                    # previous directory
cd ~user                # another user's home

ls -lah                 # long, all, human sizes
ls -lt                  # newest first
ls -lS                  # largest first

tree -L 2 -d            # directories, two levels

find

find /var/log -name '*.log' -mtime +30
find . -type f -size +100M
find . -type d -name node_modules -prune -o -type f -print
find /etc -name '*.conf' -exec grep -l 'listen' {} +
find . -type f -mmin -60          # changed in last hour

find /tmp -type f -mtime +7 -delete

Disk usage

df -hT                        # filesystems, with type
du -sh /var/*                 # size per child
du -h --max-depth=1 | sort -h
ncdu /var                     # interactive

lsof +D /var/log              # what has files open here
lsof | grep deleted           # space held by deleted files

Links and file info

ln -s /opt/app/current /usr/local/bin/app
readlink -f /usr/local/bin/app

stat file.txt
file archive.bin
sha256sum file.iso
realpath ./relative
02

Permissions

chmod and chown

chmod 640 file          # rw- r-- ---
chmod u+x,g-w file
chmod -R g+rX /srv/data # X = dirs and already-executable only

chown user:group file
chown -R www-data: /var/www
chgrp developers file

Octal reference

DigitPermission
7rwx - read + write + execute
6rw- - read + write
5r-x - read + execute
4r-- - read only
0--- - no access
755Owner full, others read+execute
644Owner read+write, others read
600Owner only - use for keys

sudo

sudo -u www-data whoami
sudo -i                     # full root login shell
sudo -l                     # what may I run
visudo -f /etc/sudoers.d/deploy

# /etc/sudoers.d/deploy
deploy ALL=(ALL) NOPASSWD: /bin/systemctl restart myapp
03

Text Processing

grep

grep -i 'error' app.log
grep -rn 'TODO' src/            # recursive with line numbers
grep -v '^#' config.conf        # invert: strip comments
grep -c 'GET' access.log        # count matches
grep -A3 -B1 'Exception' app.log
grep -E 'warn|error|fatal' app.log
grep -o '[0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+' access.log

sed

sed 's/old/new/' file           # first per line
sed 's/old/new/g' file          # all
sed -i.bak 's/old/new/g' file   # in place, keep backup
sed -n '10,20p' file            # print a line range
sed '/^#/d' config              # delete comment lines
sed 's|/old/path|/new/path|g' f # alternate delimiter

Cutting and sorting

cut -d: -f1,3 /etc/passwd
cut -c1-10 file

sort -k2 -n data.txt
sort -u list.txt
sort | uniq -c | sort -rn | head    # top offenders

tr 'a-z' 'A-Z' < file
tr -d '\r' < dos.txt > unix.txt

Viewing logs

tail -f /var/log/syslog
tail -n 200 -f app.log | grep --line-buffered ERROR
less +F app.log                  # ctrl-c to scroll, F to follow
head -50 file
zcat archive.log.gz | grep error
04

Processes

Inspecting

ps aux | grep nginx
ps -ef --forest
ps -eo pid,ppid,user,%cpu,%mem,cmd --sort=-%cpu | head

top; htop
pgrep -a nginx
pidof nginx

Signals

kill -TERM 1234       # polite (15)
kill -HUP  1234       # reload config (1)
kill -KILL 1234       # last resort (9)
pkill -f 'python app.py'
killall nginx

kill -l               # list all signals

Resource usage

free -h
vmstat 1 5
iostat -xz 1
uptime                   # load averages
nproc                    # CPU count
05

systemd

Managing units

systemctl status nginx
systemctl start|stop|restart|reload nginx
systemctl enable --now nginx
systemctl disable --now nginx
systemctl is-active nginx
systemctl is-enabled nginx

systemctl daemon-reload      # after editing unit files
systemctl list-units --failed

journalctl

journalctl -u nginx -f
journalctl -u nginx --since '1 hour ago'
journalctl -u nginx --since today --until '10:00'
journalctl -p err -b               # errors this boot
journalctl -b -1                   # previous boot
journalctl --disk-usage
journalctl --vacuum-time=7d
06

Networking

Interfaces and routes

ip a
ip -brief addr
ip r                     # routing table
ip link set eth0 up
ip a add 10.0.0.5/24 dev eth0

nmcli device status
nmcli connection show

Connections and ports

ss -tulpn                # listening TCP/UDP with process
ss -tan state established
ss -s                    # summary

lsof -i :443
nc -zv host 443          # port check
curl -sI https://example.com

DNS and reachability

dig +short example.com
dig @1.1.1.1 example.com MX
dig -x 10.0.0.5          # reverse
host example.com
resolvectl status

ping -c 4 8.8.8.8
traceroute example.com
mtr example.com
07

Storage

Block devices

lsblk -f
blkid
fdisk -l /dev/sdb
parted /dev/sdb print

mkfs.ext4 -L data /dev/sdb1
mkfs.xfs /dev/sdb1

Mounting

mount /dev/sdb1 /mnt/data
umount /mnt/data
mount -a                    # remount everything in fstab
findmnt

# /etc/fstab
# UUID=xxxx  /mnt/data  ext4  defaults,noatime  0 2
08

Users & Packages

Users and groups

useradd -m -s /bin/bash -G sudo,docker jdoe
passwd jdoe
usermod -aG developers jdoe        # -a is essential
userdel -r jdoe

id jdoe
groups jdoe
getent passwd jdoe
chage -l jdoe                      # password aging

Package managers

Taskapt / dnf
Update indexapt update / dnf check-update
Upgrade allapt upgrade / dnf upgrade
Installapt install pkg / dnf install pkg
Removeapt remove pkg / dnf remove pkg
Searchapt search x / dnf search x
What providesapt-file search f / dnf provides f
Package of a filedpkg -S f / rpm -qf f
List filesdpkg -L pkg / rpm -ql pkg

Archives and transfer

tar czf backup.tar.gz /srv/data
tar xzf backup.tar.gz -C /restore
tar tzf backup.tar.gz          # list contents

rsync -avz --progress src/ user@host:/dst/
rsync -avz --delete --dry-run src/ dst/

scp file user@host:/tmp/
09

SSH

Keys and config

ssh-keygen -t ed25519 -C 'konner@laptop'
ssh-copy-id user@host
ssh-add ~/.ssh/id_ed25519

# ~/.ssh/config
Host prod
    HostName 10.0.0.10
    User deploy
    IdentityFile ~/.ssh/id_ed25519
    ForwardAgent yes
10

Bash Scripting

Safe script header

#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'

trap 'echo "Failed at line $LINENO" >&2' ERR

SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)

Variables and defaults

name="${1:-default}"          # default if unset or empty
: "${API_URL:?must be set}"   # fail with a message

readonly MAX=10
declare -i count=0            # integer
declare -A map                # associative array
map[key]='value'

"${var,,}"                    # lowercase
"${var^^}"                    # uppercase
"${path##*/}"                 # basename
"${path%/*}"                  # dirname

Conditionals

if [[ -f "$file" ]]; then :; fi     # regular file
if [[ -d "$dir"  ]]; then :; fi     # directory
if [[ -z "$s"    ]]; then :; fi     # empty string
if [[ -n "$s"    ]]; then :; fi     # non-empty
if [[ "$a" == "$b" ]]; then :; fi
if [[ "$s" =~ ^INC[0-9]+$ ]]; then :; fi
if (( count > 10 )); then :; fi     # arithmetic

Loops and functions

for f in *.log; do
    [[ -e "$f" ]] || continue
    gzip "$f"
done

while IFS= read -r line; do
    printf '%s\n' "$line"
done < input.txt

while IFS=, read -r name email; do
    echo "$name <$email>"
done < <(tail -n +2 users.csv)

deploy() {
    local env="$1"
    echo "Deploying to ${env}"
}