Linux Commands Cheat Sheet

Your complete reference guide to essential Linux commands — from file operations and process management to networking, scripting, and beyond.

Disclaimer and Credit: GenAI created contents, prompt-engineered by Jay for FIT3184 students. Any issues or errors please email me (jay dot zhao at monash dot edu).

Directory Operations

cd — Change Directory

Description

The cd command changes the current working directory. It is one of the most frequently used commands in any Linux session.

Examples

  • cd /home/user — navigate to absolute path
  • cd .. — go up one directory level
  • cd ~ — go to home directory
  • cd - — return to previous directory
Directory Operations

mkdir & rmdir — Create and Remove Directories

mkdir

Creates a new directory. Use -p to create nested directories in one command.

  • mkdir mydir — create a directory
  • mkdir -p a/b/c — create nested dirs

rmdir

Removes an empty directory. For non-empty directories, use rm -r instead.

  • rmdir mydir — remove empty dir
  • rmdir -p a/b/c — remove nested empty dirs
Directory Operations

pwd, ls & tree — View Directory Contents

pwd

Print Working Directory — shows the full path of your current location.

pwd/home/user/projects

ls / dir

List directory contents. Use ls -la for detailed listing including hidden files.

ls -la /etc

tree

Display directory structure as a visual tree. Use -L 2 to limit depth.

tree -L 2 /var

Directory Operations

find & locate — Search for Files

find

Search for files in a directory hierarchy in real time.

  • find / -name "*.log" — find all .log files
  • find . -type d — find all directories
  • find /tmp -mtime +7 — files older than 7 days

locate

Quickly find files using a pre-built database. Run updatedb to refresh the index.

  • locate nginx.conf — find file by name
  • locate -i readme — case-insensitive search
File Operations

cp, mv & rm — Copy, Move, Delete Files

cp — Copy

Copy files or directories. Use -r for recursive copy of directories.

cp file.txt /backup/ | cp -r dir/ /backup/

mv — Move/Rename

Move files or rename them. Works across directories.

mv old.txt new.txt | mv file.txt /tmp/

rm — Remove

Delete files or directories. Use -rf with caution — it is irreversible.

rm file.txt | rm -rf /tmp/olddir

File Operations

cat, head & tail — View File Contents

cat

Concatenate and display file contents. Also used to combine files.

  • cat file.txt — display file
  • cat a.txt b.txt > c.txt — combine files

head & tail

View the beginning or end of a file. Use -n to specify line count. tail -f follows live log output.

  • head -n 20 file.txt
  • tail -f /var/log/syslog
File Operations

less & more — Paginate File Output

less

View file contents one page at a time with forward and backward navigation. Preferred over more.

  • less /var/log/auth.log
  • Press q to quit, / to search
  • Press G to jump to end

more

Similar to less but only allows forward navigation through a file.

  • more file.txt
  • Press Space to advance a page
  • Press q to quit
File Operations

touch, ln & shred — Create, Link & Destroy Files

touch

Create an empty file or update a file's timestamp.

touch newfile.txt

ln

Create hard or symbolic links between files.

ln -s /etc/nginx nginx-link

shred

Securely overwrite a file to make recovery difficult before deletion.

shred -u secret.txt

File Operations

echo, expand & fold — Text Output Utilities

echo

Print text or variable values to the terminal.

echo "Hello World" | echo $HOME

expand

Convert tabs to spaces in a file or input stream.

expand -t 4 file.txt

fold

Wrap long lines of text to a specified width.

fold -w 80 longfile.txt

Text Processing

grep, egrep & fgrep — Search Text Patterns

grep

Search for patterns in files using regular expressions. One of the most powerful Linux tools.

  • grep "error" /var/log/syslog
  • grep -r "TODO" ./src/ — recursive search
  • grep -i "warning" file.log — case-insensitive

egrep & fgrep

egrep supports extended regex (same as grep -E). fgrep treats the pattern as a fixed string, not regex.

  • egrep "error|warn" file.log
  • fgrep "192.168.1.1" access.log
Text Processing

awk & sed — Stream Editors and Text Processors

awk

A powerful pattern-scanning and processing language. Ideal for column-based data.

  • awk '{print $1}' file.txt — print first column
  • awk -F: '{print $1}' /etc/passwd
  • awk '/error/ {print}' log.txt

sed

Stream editor for filtering and transforming text. Commonly used for find-and-replace.

  • sed 's/old/new/g' file.txt
  • sed -n '5,10p' file.txt — print lines 5–10
  • sed '/^#/d' config.txt — delete comment lines
Text Processing

sort, cut & tr — Transform Text Data

sort

Sort lines of text files alphabetically or numerically.

sort file.txt | sort -n numbers.txt | sort -r file.txt

cut

Extract specific columns or fields from each line of a file.

cut -d: -f1 /etc/passwd — extract usernames

tr

Translate or delete characters from input.

echo "hello" | tr 'a-z' 'A-Z'HELLO

Text Processing

diff, cmp & split — Compare and Divide Files

diff

Compare two files line by line and show differences. Use -u for unified format (used in patches).

diff file1.txt file2.txt | diff -u old.c new.c

cmp

Compare two files byte by byte. Returns the position of the first difference.

cmp file1.bin file2.bin

split

Split a large file into smaller pieces by line count or byte size.

split -l 1000 bigfile.txt part_

Text Processing

tac, paste & join — Combine and Reverse Text

tac

Print file contents in reverse line order (opposite of cat).

tac file.txt

paste

Merge lines of files side by side, separated by a delimiter.

paste file1.txt file2.txt

join

Join lines of two files on a common field, like a database JOIN.

join file1.txt file2.txt

Text Processing

wc, fmt & column — Count and Format Text

wc — Word Count

Count lines, words, and characters in a file.

  • wc -l file.txt — count lines
  • wc -w file.txt — count words
  • wc -c file.txt — count bytes

fmt & column

fmt reformats paragraph text to a specified width. column formats input into aligned columns for readable output.

  • fmt -w 72 essay.txt
  • column -t data.txt
Process Management

ps & top — Monitor Running Processes

ps

Display a snapshot of currently running processes. Use ps aux for a full listing of all processes.

  • ps aux — all processes
  • ps -ef | grep nginx — find specific process

top / htop

top provides a real-time dynamic view of running processes. htop is an enhanced interactive version with color and mouse support.

  • top — live process monitor
  • htop — interactive process viewer
Process Management

kill, bg & fg — Control Processes

kill

Send a signal to a process, typically to terminate it. Use kill -9 to force-kill.

kill 1234 | kill -9 5678 | killall nginx

bg

Resume a suspended job in the background so the terminal remains free.

bg %1 — resume job 1 in background

fg

Bring a background job to the foreground of the current terminal.

fg %1 — bring job 1 to foreground

Process Management

strace, pmap & pidof — Inspect Processes

strace

Trace system calls and signals made by a process. Invaluable for debugging.

  • strace ls — trace ls command
  • strace -p 1234 — attach to running process

pmap & pidof

pmap reports the memory map of a process. pidof finds the PID of a running program by name.

  • pmap 1234 — memory map of PID 1234
  • pidof nginx — get nginx PID
Process Management

time, watch & mpstat — Timing and CPU Stats

time

Measure the execution time of a command.

time ./myscript.sh — shows real, user, and sys time

watch

Execute a command repeatedly at a set interval and display the output.

watch -n 2 df -h — refresh disk usage every 2s

mpstat

Report CPU statistics per processor. Part of the sysstat package.

mpstat -P ALL 1 — per-CPU stats every second

User Management

useradd, userdel & usermod — Manage Users

useradd

Create a new user account. Use -m to create a home directory.

useradd -m -s /bin/bash alice

userdel

Delete a user account. Use -r to also remove the home directory.

userdel -r alice

usermod

Modify an existing user account — change shell, group, home directory, etc.

usermod -aG sudo alice

User Management

passwd, chpasswd & chage — Manage Passwords

passwd

Change a user's password. Run as root to change any user's password.

  • passwd — change your own password
  • passwd alice — change alice's password

chpasswd & chage

chpasswd updates passwords in batch from a file. chage manages password expiry and aging policies.

  • chpasswd < users.txt
  • chage -l alice — view expiry info
  • chage -M 90 alice — set 90-day expiry
User Management

who, whoami & id — Identify Users

who

Show who is currently logged into the system, including login time and terminal.

who | who -a — all details

whoami

Print the username of the currently logged-in user.

whoamialice

id

Display user and group IDs for the current or specified user.

id | id alice — show UID, GID, groups

User Management

finger, chfn & chsh — User Info and Shell

finger

Display information about a user including login name, real name, terminal, and idle time.

  • finger alice — info about alice
  • finger — list all logged-in users

chfn & chsh

chfn changes a user's full name and contact info. chsh changes the default login shell.

  • chfn alice — update finger info
  • chsh -s /bin/zsh alice — set zsh as shell
File Permissions

chmod — Change File Permissions

Description

Change the read, write, and execute permissions of files and directories. Permissions can be set using symbolic or octal notation.

Examples

  • chmod 755 script.sh — rwxr-xr-x
  • chmod +x script.sh — add execute
  • chmod -R 644 /var/www — recursive
  • chmod u+w,g-r file.txt — symbolic mode
File Permissions

chown, chattr & mount — Ownership and Attributes

chown

Change the owner and/or group of a file or directory.

chown alice:staff file.txt | chown -R www-data /var/www

chattr

Change special file attributes on Linux filesystems (e.g., make a file immutable).

chattr +i file.txt — make immutable

mount

Mount a filesystem or device to a directory in the file tree.

mount /dev/sdb1 /mnt/usb

Group Management

groupadd, groupdel & groupmod — Manage Groups

groupadd & groupdel

Create or delete a user group on the system.

  • groupadd developers — create group
  • groupdel developers — delete group

groupmod & groups

groupmod modifies a group's name or GID. groups lists all groups a user belongs to.

  • groupmod -n devs developers
  • groups alice — show alice's groups
Group Management

gpasswd & grpck — Group Passwords and Verification

gpasswd

Administer /etc/group and /etc/gshadow. Add or remove users from groups and set group passwords.

gpasswd -a alice developers — add alice to group

gpasswd -d alice developers — remove alice

grpck

Verify the integrity of group files. Checks for invalid entries in /etc/group and /etc/gshadow.

grpck — run group file integrity check

Networking

ping & traceroute — Test Network Connectivity

ping

Send ICMP echo requests to test if a host is reachable and measure round-trip time.

  • ping google.com
  • ping -c 4 192.168.1.1 — send 4 packets

traceroute / tracepath

Trace the route packets take to reach a destination, showing each hop along the way.

  • traceroute google.com
  • tracepath 8.8.8.8 — no root required
Networking

ifconfig & ip — Network Interface Configuration

ifconfig

Display or configure network interfaces. Older tool, largely replaced by ip on modern systems.

  • ifconfig — show all interfaces
  • ifconfig eth0 up — bring interface up

ip

Modern replacement for ifconfig, route, and arp. Manages addresses, routes, and links.

  • ip addr show — show IP addresses
  • ip route show — show routing table
  • ip link set eth0 up
Networking

ssh & scp — Secure Remote Access and Transfer

ssh

Securely connect to a remote machine over an encrypted channel.

ssh alice@192.168.1.10

ssh -p 2222 alice@server.com

scp

Securely copy files between hosts over SSH.

scp file.txt alice@server:/tmp/

scp -r /local/dir alice@server:/remote/

rsync

Efficiently sync files locally or over SSH, transferring only changed data.

rsync -avz /src/ alice@server:/dst/

Networking

curl & wget — Download Files from the Web

curl

Transfer data from or to a server using various protocols. Highly versatile for API testing and downloads.

  • curl https://example.com
  • curl -O https://example.com/file.zip
  • curl -X POST -d '{"key":"val"}' api.com

wget

Non-interactive downloader supporting HTTP, HTTPS, and FTP. Great for recursive downloads.

  • wget https://example.com/file.tar.gz
  • wget -r https://example.com — recursive
  • wget -c file.zip — resume download
Networking

netstat, iptables & nmcli — Network Status and Firewall

netstat

Display network connections, routing tables, and interface statistics.

netstat -tuln — show listening ports

iptables

Configure Linux kernel firewall rules for packet filtering and NAT.

iptables -L — list rules | iptables-save > rules.txt

nmcli

Command-line tool for NetworkManager — manage connections, Wi-Fi, and VPNs.

nmcli con show | nmcli dev wifi connect SSID

Networking

hostname, nslookup & host — DNS and Host Info

hostname

Display or set the system's hostname. hostnamectl provides more control on systemd systems.

hostname | hostnamectl set-hostname myserver

nslookup

Query DNS servers to resolve domain names to IP addresses and vice versa.

nslookup google.com | nslookup 8.8.8.8

host

Simple DNS lookup utility. Converts names to IPs and IPs to names.

host google.com | host 8.8.8.8

Networking

nc (netcat), arp & vnstat — Advanced Network Tools

nc (netcat)

The "Swiss Army knife" of networking — read/write data across TCP/UDP connections. Used for port scanning, file transfer, and debugging.

  • nc -zv host 80 — test port 80
  • nc -l 1234 > file.txt — receive file

arp & vnstat

arp displays and modifies the ARP cache (IP-to-MAC mappings). vnstat monitors network traffic usage over time.

  • arp -a — show ARP table
  • vnstat -i eth0 — traffic stats
Package Management

apt, apt-get & aptitude — Debian Package Management

apt

Modern, user-friendly package manager for Debian/Ubuntu. Combines the best of apt-get and apt-cache.

apt update && apt upgrade | apt install nginx

apt-get

Classic package management tool. Preferred in scripts for its stable interface.

apt-get install vim | apt-get remove vim

aptitude

Advanced package manager with a text-based UI and better dependency resolution.

aptitude install nginx | aptitude search vim

Job Scheduling

cron & crontab — Schedule Recurring Jobs

cron / crontab

Schedule commands to run automatically at specified times. Edit your crontab with crontab -e. The cron syntax is: minute hour day month weekday command.

Examples

  • crontab -e — edit cron jobs
  • crontab -l — list cron jobs
  • 0 2 * * * /backup.sh — run at 2am daily
  • */5 * * * * /check.sh — every 5 minutes
Job Scheduling

at, atq & atrm — One-Time Job Scheduling

at

Schedule a command to run once at a specific time in the future.

echo "reboot" | at 02:00

at now + 1 hour — then type commands

atq

List pending jobs in the at queue.

atq — show all queued jobs

atrm

Remove a job from the at queue by its job number.

atrm 3 — remove job number 3

Disk & Filesystem

df & du — Disk Space Usage

df — Disk Free

Report the amount of disk space used and available on filesystems.

  • df -h — human-readable sizes
  • df -T — show filesystem type
  • df /home — specific mount point

du — Disk Usage

Estimate file and directory space usage.

  • du -sh /var/log — total size of dir
  • du -ah /home — all files with sizes
  • du -sh * | sort -h — sorted by size
Disk & Filesystem

fdisk, cfdisk & mkfs — Partition and Format Disks

fdisk

Partition table manipulator for MBR disks. Use gdisk for GPT.

fdisk -l — list partitions | fdisk /dev/sdb

cfdisk

Curses-based interactive partition editor — easier to use than fdisk.

cfdisk /dev/sdb

dosfsck

Check and repair FAT filesystems (MS-DOS file system checker).

dosfsck -a /dev/sdb1 — auto-repair

Disk & Filesystem

dump, restore & sync — Backup and Sync

dump & restore

dump creates backups of ext2/3/4 filesystems. restore recovers files from those backups.

  • dump -0uf /backup/root.dump /
  • restore -rf /backup/root.dump

sync

Flush filesystem buffers, writing all pending data to disk. Run before unmounting a device.

  • sync — flush all buffers to disk
  • Always run before umount on removable media
Compression & Archiving

tar — Archive Files

Description

tar creates and extracts archive files. Combine with compression tools like gzip or bzip2 for compressed archives.

Examples

  • tar -czf archive.tar.gz /dir — create gzip archive
  • tar -xzf archive.tar.gz — extract gzip archive
  • tar -cjf archive.tar.bz2 /dir — bzip2 archive
  • tar -tf archive.tar.gz — list contents
Compression & Archiving

gzip, bzip2 & zip — Compress Files

gzip / gunzip

Compress or decompress files using the GNU zip algorithm.

gzip file.txtfile.txt.gz

gunzip file.txt.gz

bzip2 / bunzip2

Higher compression ratio than gzip, but slower. Produces .bz2 files.

bzip2 file.txtfile.txt.bz2

zip / unzip

Create and extract ZIP archives, compatible with Windows.

zip archive.zip file1 file2

unzip archive.zip

Hardware & System Info

uname, lsblk & lsusb — System and Device Info

uname

Print system information including kernel name, version, and architecture.

uname -a — all info | uname -r — kernel version

lsblk

List block devices (disks, partitions, and their mount points) in a tree format.

lsblk | lsblk -f — show filesystems

lsusb / lshw

lsusb lists USB devices. lshw provides detailed hardware configuration.

lsusb | lshw -short

Hardware & System Info

free, iostat & hdparm — Memory and Disk Performance

free

Display the amount of free and used memory in the system, including swap.

  • free -h — human-readable output
  • free -m — output in megabytes

iostat & hdparm

iostat reports CPU and I/O statistics for devices. hdparm gets or sets hard disk parameters.

  • iostat -x 1 — extended stats every 1s
  • hdparm -I /dev/sda — disk info
  • hdparm -tT /dev/sda — benchmark disk
Hardware & System Info

dmesg, dmidecode & acpi — Kernel and Hardware Diagnostics

dmesg

Print or control the kernel ring buffer — useful for diagnosing hardware and boot issues.

dmesg | tail -20 | dmesg | grep error

dmidecode

Dump DMI/SMBIOS data — shows hardware info like CPU, RAM, BIOS, and motherboard details.

dmidecode -t memory | dmidecode -t bios

acpi

Show battery status, AC adapter state, and thermal information on laptops.

acpi -b — battery | acpi -t — temperature

System Control

systemctl — Control System Services

Description

systemctl is the primary tool for managing systemd services and the system state. Start, stop, enable, and inspect services.

Examples

  • systemctl start nginx — start service
  • systemctl stop nginx — stop service
  • systemctl enable nginx — start on boot
  • systemctl status nginx — check status
  • systemctl list-units — list all units
System Control

halt, reboot, poweroff & shutdown — Power Management

halt

Halt the system immediately, stopping all processes without powering off.

halt | halt -f — force halt

reboot

Restart the system gracefully, shutting down all services first.

reboot | reboot -f — force reboot

poweroff & shutdown

poweroff halts and powers off the machine. shutdown schedules a shutdown with an optional message.

shutdown -h now | shutdown -r +5 "Rebooting"

Logging & Monitoring

journalctl & sar — System Logs and Performance

journalctl

Query and display logs from the systemd journal. The primary logging tool on modern Linux systems.

  • journalctl -xe — recent errors
  • journalctl -u nginx — service logs
  • journalctl --since "1 hour ago"

sar

Collect, report, and save system activity information (CPU, memory, I/O). Part of the sysstat package.

  • sar -u 1 5 — CPU usage, 5 samples
  • sar -r — memory stats
  • sar -b — I/O stats
Logging & Monitoring

vmstat, uptime & dstat — System Performance Overview

vmstat

Report virtual memory, processes, I/O, and CPU activity statistics.

vmstat 1 5 — 5 reports, 1 second apart

uptime

Show how long the system has been running, plus load averages for 1, 5, and 15 minutes.

uptimeup 3 days, load average: 0.5, 0.3, 0.2

dstat

Versatile resource statistics tool combining vmstat, iostat, and netstat output.

dstat -cdngy — CPU, disk, net, page, sys

Logging & Monitoring

script & last — Session Recording and Login History

script

Record everything printed to the terminal into a file. Useful for auditing and documentation.

  • script session.log — start recording
  • exit — stop recording
  • scriptreplay timing.log session.log

last

Show a listing of last logged-in users, reading from /var/log/wtmp.

  • last — all recent logins
  • last alice — logins for alice
  • last reboot — system reboots
Checksum & Integrity

md5sum, cksum & sum — Verify File Integrity

md5sum

Compute or verify MD5 checksums to confirm file integrity after download or transfer.

md5sum file.iso | md5sum -c checksums.md5

cksum

Calculate a CRC checksum and byte count for a file.

cksum file.txt — outputs checksum and size

sum

Compute a simple checksum and block count for a file.

sum file.txt — legacy checksum tool

Date & Time

date, cal & hwclock — Date and Time Commands

date

Display or set the system date and time. Supports custom format strings.

date | date "+%Y-%m-%d %H:%M" | date -s "2024-01-01 12:00"

cal

Display a calendar for the current or specified month and year.

cal | cal 12 2024 — December 2024

hwclock

Read or set the hardware (BIOS) clock. Sync it with the system clock.

hwclock --show | hwclock --systohc

Shell & Scripting

alias & export — Shell Customization

alias

Create shortcuts for long or frequently used commands. Add to ~/.bashrc for persistence.

  • alias ll='ls -la'
  • alias gs='git status'
  • unalias ll — remove alias

export

Set environment variables and make them available to child processes.

  • export PATH=$PATH:/usr/local/bin
  • export EDITOR=vim
  • export -p — list all exported vars
Shell & Scripting

if, for & while — Shell Control Flow

if / else

Conditional execution based on exit status or test expressions.

if [ -f file.txt ]; then echo "exists"; fi

for

Iterate over a list of items or a range of numbers.

for i in 1 2 3; do echo $i; done

while / until

Execute commands repeatedly while or until a condition is true.

while true; do sleep 1; done

Shell & Scripting

read, printf & eval — Input and Output in Scripts

read

Read a line of input from the user or a file into a variable.

read -p "Enter name: " name

echo $name

printf

Format and print data, similar to C's printf. More powerful than echo.

printf "Hello, %s!\n" "$name"

eval

Evaluate and execute a string as a shell command. Use with caution.

cmd="ls -la"; eval $cmd

Shell & Scripting

declare, source & type — Variable and Script Management

declare

Declare variables and give them attributes (integer, array, read-only, etc.).

  • declare -i num=5 — integer variable
  • declare -r PI=3.14 — read-only
  • declare -a arr=(1 2 3) — array

source & type

source (or .) executes a script in the current shell, loading its variables. type shows how a command name is interpreted.

  • source ~/.bashrc
  • type ls — is it alias, function, or binary?
Shell & Scripting

expr, factor & seq — Math and Sequences

expr

Evaluate arithmetic and string expressions in shell scripts.

expr 5 + 38

expr length "hello"5

factor

Print the prime factorization of a given number.

factor 6060: 2 2 3 5

seq

Generate a sequence of numbers with optional step and format.

seq 1 10 | seq 0 2 10 — even numbers

Shell & Scripting

expect & setsid — Automation and Session Control

expect

Automate interactive command-line programs by scripting expected prompts and responses. Useful for automating SSH logins and FTP sessions.

  • expect script.exp — run expect script
  • Uses spawn, expect, send commands

setsid

Run a program in a new session, detached from the controlling terminal. Useful for daemonizing processes.

  • setsid ./myscript.sh
  • Process continues after terminal closes
Kernel & Modules

lsmod, insmod & rmmod — Kernel Module Management

lsmod

List currently loaded kernel modules and their dependencies.

lsmod | lsmod | grep bluetooth

insmod

Insert a module into the Linux kernel. Requires the full path to the .ko file.

insmod /lib/modules/mymod.ko

rmmod

Remove a loaded module from the kernel. Use modprobe -r for safer removal with dependency handling.

rmmod mymod

Kernel & Modules

depmod & modinfo — Module Dependencies and Info

depmod

Generate a list of module dependencies and map files. Run after installing a new kernel module.

  • depmod -a — update all module dependencies
  • Required before modprobe can find new modules

modinfo

Display information about a kernel module — author, description, parameters, and license.

  • modinfo bluetooth
  • modinfo -F description e1000
Development & Build

gcc, g++ & gdb — Compile and Debug Code

gcc

GNU C Compiler — compile C source files into executables.

gcc -o myapp main.c | gcc -Wall -g main.c

g++

GNU C++ Compiler — compile C++ source files.

g++ -o myapp main.cpp | g++ -std=c++17 main.cpp

gdb

GNU Debugger — step through code, set breakpoints, and inspect variables at runtime.

gdb ./myapp | gdb -p 1234 — attach to process

Development & Build

autoconf, automake & make — Build Automation

autoconf & automake

Generate portable configure scripts and Makefile.in templates for building software across different platforms.

  • autoconf — generate configure script
  • automake --add-missing
  • autoreconf -i — run all auto tools

ctags & readelf

ctags generates tag files for source code navigation in editors. readelf displays information about ELF binary files.

  • ctags -R . — tag all source files
  • readelf -h myapp — ELF header info
Development & Build

cpp, addr2line & ranlib — Preprocessor and Binary Tools

cpp

The C preprocessor — expands macros, includes, and conditional compilation directives before compilation.

cpp main.c | cpp -DDEBUG main.c

addr2line

Convert program addresses into file names and line numbers for debugging crash reports.

addr2line -e myapp 0x4005f0

ranlib

Generate an index for a static library archive, making linking faster.

ranlib libmylib.a

Help & Documentation

man, info & apropos — Get Help

man

Display the manual page for a command. The most important help tool in Linux.

  • man ls — manual for ls
  • man 5 passwd — section 5 of passwd
  • man -k keyword — search manuals

info, apropos & whatis

info provides more detailed GNU documentation. apropos searches man page descriptions. whatis gives a one-line description.

  • info bash
  • apropos network
  • whatis ls | which python3
Terminal & Sessions

screen & tmux — Terminal Multiplexers

screen

Create multiple terminal sessions within one window. Sessions persist after disconnection — ideal for remote work.

  • screen — start new session
  • screen -r — reattach to session
  • Ctrl+A D — detach from session

stty, tty & reset

stty configures terminal settings. tty prints the terminal device name. reset reinitializes a garbled terminal.

  • stty -a — show all settings
  • tty/dev/pts/0
  • reset — fix broken terminal
Terminal & Sessions

agetty, chvt & showkey — Console Management

agetty

Open a terminal line and invite a login. Used by init/systemd to manage virtual console logins.

agetty tty1 38400 — open login on tty1

chvt

Change the active virtual terminal (console). Equivalent to pressing Ctrl+Alt+F1.

chvt 2 — switch to virtual terminal 2

showkey

Display the keycodes or scancodes of keys pressed on the keyboard. Useful for keyboard mapping.

showkey — show keycodes | showkey -s — scancodes

Printing & Media

cupsd, aplay & amixer — Printing and Audio

cupsd

The CUPS print server daemon. Manages print queues and printer drivers on Linux.

systemctl start cups | Access at http://localhost:631

aplay

Play audio files from the command line using ALSA.

aplay sound.wav | aplay -l — list sound cards

amixer

Control ALSA sound card mixer settings from the command line.

amixer set Master 80% | amixer get Master

Mail & Communication

mail, write & wall — User Communication Commands

mail & mailq

mail sends and reads email from the command line. mailq displays the mail transfer agent's queue of pending messages.

  • echo "Hello" | mail -s "Subject" user@host
  • mailq — show pending mail queue

write & wall

write sends a message to a specific logged-in user. wall broadcasts a message to all logged-in users.

  • write alice pts/1 — message to alice
  • wall "System going down in 5 min"
  • biff y — notify on new mail
I/O Redirection

Output Redirection — >, >>, 2>, &>

> (Overwrite)

Redirect stdout to a file, overwriting existing content.

ls > files.txt — save listing to file

>> (Append)

Redirect stdout to a file, appending to existing content.

echo "log entry" >> app.log

2> and &>

Redirect stderr (2>) or both stdout and stderr (&>) to a file.

cmd 2> err.log | cmd &> all.log

I/O Redirection

Pipes and Input Redirection — |, <, <<

Pipe — |

Send the output of one command as input to another. The backbone of Linux command chaining.

  • ps aux | grep nginx
  • cat file.txt | sort | uniq
  • ls -la | less

Input — < and <<

< redirects a file as stdin to a command. << (here-doc) provides inline multi-line input.

  • sort < unsorted.txt
  • cat << EOF — start here-doc
  • mysql db < script.sql
Vim Editor

Vim — Essential Navigation and Editing

Vim is a powerful terminal text editor. Understanding its modal nature is key — press i to enter Insert mode, Esc to return to Normal mode, and :wq to save and quit.

Vim Editor

Vim — Navigation, Search & Replace

Navigation

  • gg — go to beginning of file
  • G — go to end of file
  • 0 — go to beginning of line
  • $ — go to end of line
  • Ctrl+F — scroll forward one page

Search

  • /pattern — search forward
  • ?pattern — search backward
  • n — next match | N — previous match
  • * — search word under cursor

Replace

  • :s/old/new/ — replace first on line
  • :s/old/new/g — replace all on line
  • :%s/old/new/g — replace all in file
  • :g/pattern/d — delete matching lines
Vim Editor

Vim — Editing, Deletion & Buffers

Editing Commands

  • dd — delete current line
  • D — delete to end of line
  • dw — delete word forward
  • db — delete word backward
  • yy — copy (yank) current line
  • p — paste after cursor
  • u — undo | Ctrl+R — redo

Buffers and Files

  • :w — save file
  • :q! — quit without saving
  • :wq — save and quit
  • :e file.txt — open another file
  • :split file.txt — horizontal split
  • Ctrl+W W — switch between splits
  • :bn / :bp — next/prev buffer