Linux Tips and Tricks

Introduction
A collection of commands that I struggle to remember ...

Disk Usage
Find which directory or file occupies the most disk space, in the current filesystem: du -h --max-depth=1 --one-file-system. 2>/dev/null | sort -h

Find which directory or file occupies the most disk space: du -sh * 2>/dev/null | sort -h

Report file system disk space usage: df -T -h -x devtmpfs -x tmpfs -x squashfs

Report file system inodes usage: df -T -h -x devtmpfs -x tmpfs -x squashfs -i

Search for files and directories
Find all directories under /opt, excluding the path /opt/Citrix: find /opt -not -path "/opt/Citrix" -not -path "/opt/Citrix/*" -type d 2>/dev/null

Regular Expressions
Match an IP address: ([0-9]{1,3}[\.]){3}[0-9]{1,3}

Dump network traffic
Good for capturing web pages: tcpdump -i any -n -A -s 0 -w /tmp/capture.cap 'tcp port 80'

Good for capturing generic traffic: tcpdump -i any -n -X -s 0 -w /tmp/capture.cap 'tcp and host 192.168.1.2'

The idempotent way
Create an empty file: touch /path/to/file.txt

Create a directory: mkdir -p /path/to/dir

Create a symbolic link: ln -sfn source target

Remove a file: rm -f /path/to/file.txt

X server display
To keep the diplay settings after changing user: echo $DISPLAY xauth list su - user export DISPLAY=output of the first command xauth add output of the second command

Swap
Display swap usage by device: swapon --show --output-all

Get current swap usage for all running processes: SUM=0; for DIR in $(find /proc/ -maxdepth 1 -type d -regex "^/proc/[0-9]+") do    PID=$(echo $DIR | cut -d / -f 3) PROGNAME=$(ps -p $PID -o comm --no-headers) for SWAP in $(grep VmSwap $DIR/status 2>/dev/null | awk '{ print $2 }') do        let SUM=$SUM+$SWAP done if (( $SUM > 0 )); then echo "PID=$PID swapped $SUM KB ($PROGNAME)" fi    SUM=0 done | sort -n -k3