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 -hT -x devtmpfs -x tmpfs -x squashfs -x fuse duf -only local -style ascii

Report file system inodes usage: df -hT -x devtmpfs -x tmpfs -x squashfs -x fuse -i duf -only local -style ascii -inodes

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 -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 sudo -u newuser -i echo $DISPLAY xauth add $(xauth -f ~USER/.Xauthority list | tail -n 1)

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

Users and Groups
Add a user to a group: usermod -a -G testgroup testuser

Remove a user from a group: gpasswd -d testuser testgroup Removing user testuser from group testgroup

tmux
Create a new session named mysession: tmux new -s mysession

Exit (detach) current session: Ctrl-b d

Re-entering (attach) the session named mysession: tmux attach -t mysession

List available sessions: tmux ls

Split pane with horizontal layout: Ctrl+b %

Toggle last active pane: Ctrl+b ;

Switch to pane to the direction: Ctrl+b ↑ ↓ → ← (arrow keys)

Linux Audit daemon
Summary Report: aureport -ts today -i --summary

Event Summary Report: aureport -ts today -i --summary -e

Syscall Summary Report: aureport -ts today -i --summary -s

Journalctl
See all errors since last boot: journalctl --priority=3 --catalog --boot

See all of today's errors: journalctl --priority=3 --catalog --since=today

Follows the mysql service logs: journalctl --unit=mysql.service --follow

List the boots of the system: journalctl --list-boots