Reference

Linux command manual

304 commands explained with syntax, options, copy-ready examples and each one's typical mistakes. It is the cheat sheet that goes with the course.

304 commands

pwd

Prints the full path of the folder you are in. It is your reference when you get lost.

ls

Lists the content of a folder. With no arguments, the current one.

cd

Changes folder. It is the command you will use most in your whole terminal life.

tree

Draws the tree of folders and files, like a diagram.

touch

Creates an empty file or updates its modification date.

mkdir

Creates folders. With -p it also creates any missing parents.

cp

Copies files. For whole folders it needs -r.

mv

Moves files or folders. It also renames.

rm

Deletes files. With -r, whole folders. There is no recycle bin.

rmdir

Deletes folders, but only if they are empty. It is the safe option.

ln

Creates links: a shortcut to another file on the system.

stat

Shows the full technical record of a file: size, permissions, dates and owner.

cat

Shows the whole content of a file. It also joins several on screen.

less

Opens the file page by page: you can move, search and quit whenever you want.

head

Shows the first lines of a file (10 by default).

tail

Shows the last lines of a file. The log watcher's command.

wc

Counts lines, words and characters. With pipes it is a result counter.

grep

Searches a pattern inside files and shows only the matching lines.

find

Finds files and folders by name, type or size inside a tree.

which

Tells the path of the program that runs when you type a command.

sort

Sorts the lines of a file or of the input. Alphabetical by default.

uniq

Removes consecutive repeated lines and, with -c, counts them.

cut

Cuts columns or fields from each line. Ideal for separated listings.

tr

Changes or deletes characters. Very useful to uppercase or clean text.

sed

Edits text as a stream: above all, replaces words inside lines.

awk

Processes text by columns and lets you filter and compute in one line.

echo

Prints text on screen. With redirection, it writes to files.

chmod

Changes the permissions of a file or folder. The basis of Linux security.

chown

Changes the owner of a file. It needs administrator privileges.

chgrp

Changes the group a file belongs to.

umask

Defines which permissions are REMOVED from new files you create.

whoami

Tells which user you are working as right now.

id

Shows your user number, your main group and the groups you belong to.

su

Switches user inside the same session. It asks for the other user's password.

useradd

Creates a new user account. It requires administrator privileges.

userdel

Deletes a user account. With -r it also deletes their home folder.

passwd

Changes a user's password. With no arguments, your own.

ps

Shows the processes running on the system.

df

Shows the free and used space of mounted disks.

du

Measures how much a folder or file takes. The space detective.

free

Shows the available RAM and swap area.

uname

Shows system information: kernel, architecture and host name.

uptime

Tells how long the machine has been on and the system load average.

ping

Checks whether a host responds and how long it takes.

traceroute

Shows the path a packet travels to its destination, hop by hop.

ip

Inspects and configures the network: addresses, routes and interfaces.

ifconfig

The classic to see network configuration. Today ip is preferred.

ss

Lists the connections and ports listening on your machine.

ssh

Opens a session on another machine, encrypted. The gateway to servers.

scp

Copies files between your machine and another over the ssh connection.

curl

Requests a URL and shows the response. The command to talk to web services.

wget

Downloads files from the internet with a single command.

apt

The Debian and Ubuntu package manager: installs, searches and updates software.

tar

Packs files and folders into a single file, with or without compression.

history

Shows the commands you have typed in this session, numbered.

alias

Creates custom shortcuts for long commands.

export

Defines environment variables: named values your programs use.

env

Shows all current environment variables.

man

Opens the official manual of a command: Linux's source of truth.

kill

Sends a signal to a process to ask it to finish, pause it or resume it. It is how you tell a program to stop.

pgrep

Finds processes by name and returns their PIDs. It is pkill's sibling without killing anything.

pkill

Kills processes by name, without looking up the PID first.

sleep

Pauses execution for a while. Very useful in scripts to wait between steps.

top

Shows a snapshot of every process sorted by usage, with the load and memory summary on top.

htop

A more visual alternative to top, with CPU and memory bars and colours. Many people's favourite.

nice

Runs a command with lower priority so it does not hog the CPU. It goes from -20 (highest) to 19 (lowest).

renice

Changes the priority of a process that is already running.

jobs

Lists the jobs launched in the background from this terminal, with their number and state.

fg

Brings a background or stopped job back to the foreground.

bg

Resumes a stopped job in the background, so it keeps going without occupying the terminal.

nohup

Runs a command so it keeps working even if you close the terminal. Output is saved to nohup.out.

watch

Repeats a command every few seconds to watch for a change: memory, space, connections...

timeout

Runs a command and stops it if it takes longer than allowed. Ideal for scripts and tests.

systemctl

Manages the system's services (units): start, stop, check whether they are active and decide whether they start with the machine.

journalctl

Reads the system log, where the messages from services and the kernel end up.

dmesg

Shows the kernel messages since boot: detected hardware, disks, network and errors.

service

The old (SysV) way of managing services. It still works, but systemctl is used today.

date

Shows the current date and time. With +FORMAT you can extract just the part you need for file names or reports.

who

Lists the users with a session open right now, with their terminal and where they connected from.

last

Shows the history of logins and logouts. Useful to know when the machine was used and to spot unusual access.

crontab

Manages your scheduled tasks: commands the system runs on its own at certain times or days.

printf

Prints formatted text. Unlike echo, it reliably interprets sequences such as \n (newline) or \t (tab).

tee

Shows the output on screen and saves it to a file at the same time. It is the 'T' of a pipeline: it writes to two places.

xargs

Turns one command's output into arguments for another. Used when a command does not accept piped input.

diff

Compares two files line by line and shows the differences. It is the basis of patches and version control.

jq

Processes and formats JSON from the terminal: extracts fields, filters and shows API data readably.

whereis

Locates the binary, the source code and the manual pages of a command.

pstree

Shows processes as a tree: who launched whom. It is the best way to see the process hierarchy.

pidof

Returns the PID of a program by name. Handy for scripts that need the exact number.

killall

Sends a signal to every process sharing a name. Useful to close at once a program opened many times.

lscpu

Summarises the processor: architecture, cores, threads, frequency and cache. All without opening the machine.

hostnamectl

Shows and changes the machine name and machine data (operating system, kernel, architecture).

timedatectl

Shows and adjusts the time, the time zone and network synchronisation (NTP).

cal

Shows a calendar of the month or the year in the terminal.

w

Shows who is logged in and what they are doing, plus the system load average.

vmstat

Reports the state of memory, swap, disk I/O and CPU usage in a single table.

locale

Shows the locale configuration: language, number format, dates and alphabetical sorting.

lsblk

Lists disks and their partitions as a tree, with sizes and mount points.

blkid

Shows the UUID and filesystem type of each device. Key to mounting by UUID.

findmnt

Shows mounted filesystems as a tree, indicating which device is at each mount point.

mount

Mounts a device into a folder so you can access its contents, or lists what is already mounted.

umount

Unmounts a device or a folder that was mounted, leaving it ready to be safely removed.

fdisk

Views and edits a disk's partitions. With -l it shows the table without entering interactive mode.

mkfs.ext4

Formats a partition with the ext4 filesystem, the Linux standard.

mkfs.vfat

Formats a partition as FAT32, the format compatible with Windows, cameras and almost any device.

dd

Copies data at a low level, block by block. Used to clone disks, create images and fill files.

mkswap

Prepares a partition or file to be used as swap memory.

swapon

Enables swap memory and shows which one is in use.

swapoff

Disables swap memory, returning its contents to RAM.

fsck

Checks and repairs the integrity of a filesystem. It is Linux's 'chkdsk'.

setfacl

Grants fine-grained permissions to specific users or groups without changing the owner or the basic mode.

getfacl

Shows the access control list (ACL) of a file or folder.

chattr

Changes special file attributes, such as making it immutable so not even root can delete it.

lsattr

Lists the special attributes of files (such as immutable).

groupadd

Creates a new group in the system.

groupdel

Deletes a group from the system.

groupmod

Modifies an existing group, for example renaming it.

groups

Shows which groups a user belongs to. With no arguments, the current user.

usermod

Modifies a user account: groups, shell, home directory, account lock, and more.

chage

Views and changes a password's expiry: when it expires and how often it must be changed.

chsh

Changes a user's default shell.

getent

Queries the system databases (users, groups, hosts). It is the right way to check whether an account or group exists.

newgrp

Changes the effective group of the current session without logging out.

ufw

Ubuntu's simple firewall. Enables protection and decides which ports are allowed or blocked.

iptables

Linux's low-level firewall: chains of rules that filter network traffic.

ssh-keygen

Generates an SSH key pair (public and private) to connect to servers without a password.

ssh-copy-id

Copies your public key to the remote server so you can log in over SSH without a password.

nc

The network 'Swiss army knife': checks whether a port is open, transfers data or listens.

lsof

Lists the files opened by processes. With -i, it shows which processes use the network and which ports listen.

dig

Queries DNS servers and shows the full answer: IP address, servers and timings.

host

Resolves domain names to IP addresses and back, with short output.

nslookup

Queries DNS interactively or directly. Classic and also available on Windows.

nmcli

Controls network connections from the terminal: device status, wifi networks and connection profiles.

arp

Shows the ARP table: the mapping between local IP addresses and network MAC addresses.

route

Shows the routing table: where traffic leaves for each network and what the gateway is.

ethtool

Shows and adjusts a network card's parameters: speed, duplex and whether the cable is connected.

tcpdump

Captures the network traffic passing through an interface, to troubleshoot or study protocols.

nmap

Scans hosts and ports to discover which services are exposed. A basic auditing tool.

seq

Generates a sequence of numbers. Perfect for loops, tests and generating data.

nl

Numbers the lines of a file. It is like cat -n but with fine control of the format.

rev

Reverses the character order of each line. Fun and useful for some text tricks.

tac

Shows a file with the lines in reverse order: the last first. It is 'cat' backwards.

fold

Wraps long lines into chunks of a given width. Useful to fit text to a screen or page.

fmt

Reformats paragraphs: joins the lines and splits them again to fill a uniform width.

column

Organises text into aligned columns. With -t it turns messy output into a clean table.

paste

Joins lines from several files into one, sticking them side by side separated by a tab.

split

Splits a large file into smaller chunks. Very useful to upload or move files in parts.

comm

Compares two sorted files and shows in columns which lines are only in the first, only in the second or shared.

join

Combines two files by a common field, like a database query but with text.

cmp

Compares two files byte by byte and says exactly at which byte and line they differ.

base64

Encodes data into safe text (only letters, numbers, + and /) and decodes it back. Useful to embed binaries in text.

xxd

Shows a file in hexadecimal and its text equivalent, byte by byte. Essential to inspect binary data.

od

Dumps a file in octal (or other formats) showing its bytes, useful to inspect raw data.

iconv

Converts text between character encodings, for example from UTF-8 to ASCII or Latin-1.

dos2unix

Converts a file from Windows line endings (CRLF) to Unix (LF). Fixes the classic ^M error.

unix2dos

Converts a file from Unix line endings (LF) to Windows (CRLF).

gzip

Compresses a file with the gzip algorithm and adds the .gz extension. It is the de facto standard on Linux.

gunzip

Decompresses .gz files and recovers the original.

zcat

Shows the contents of a .gz file without decompressing it to disk. It is cat + gunzip.

bzip2

Compresses files with the bzip2 algorithm (.bz2), which usually packs more than gzip at the cost of speed.

bunzip2

Decompresses .bz2 files.

bzcat

Shows the contents of a .bz2 file without decompressing it to disk.

xz

Compresses files with the xz algorithm (.xz), the best compressor of the three classics.

unxz

Decompresses .xz files.

xzcat

Shows the contents of a .xz file without decompressing it to disk.

zip

Creates .zip compressed archives, the format most compatible with Windows, macOS and almost any program.

unzip

Extracts .zip files and can list their contents without extracting.

file

Guesses a file's real type by looking at its content, not its extension. Very useful when you do not know what it is.

true

Does nothing and exits successfully (code 0). Its use is in scripts, for infinite loops or default values.

false

Does nothing and exits with an error (code 1). The complement of true.

type

Says what a name is: a binary, a shell builtin or an alias. It answers 'why does this command behave like this'.

source

Runs a command file in the current shell, so the variables and functions it defines stay in your session.

set

With no arguments, shows every shell variable. It also changes shell behaviour options.

unset

Deletes a variable or function from the shell.

readonly

Marks a variable as read-only: it cannot be changed or deleted during the session.

let

Performs arithmetic and stores the result in variables, right on the command line.

expr

Evaluates simple arithmetic and logical expressions from the command line.

bc

Arbitrary-precision calculator. Unlike the shell, it handles decimals without losing precision.

mktemp

Creates a temporary file or folder with a unique, safe name, so it does not clash with others.

ulimit

Shows or limits the resources your session can consume: open files, processes, memory, etc.

dpkg

Manages .deb packages directly: install them, list them or check which package a file belongs to.

apt-cache

Queries the package catalogue without installing anything: search, view details or check the available version.

snap

Manages snap packages: applications bundled with all their dependencies that update themselves.

shutdown

Shuts down or restarts the machine in an orderly way, warning users and closing programs.

reboot

Restarts the machine immediately.

poweroff

Powers off the machine immediately, in an orderly way.

halt

Stops the system without necessarily cutting the power. Classic way to halt the machine.

at

Schedules a command to run once at a specific time.

atq

Lists the pending tasks scheduled with at.

atrm

Deletes a task scheduled with at, by its number.

strace

Runs a program showing the system calls it makes. It is the magnifying glass to understand what it really touches.

fuser

Says which processes are using a file, a folder or a port. Very useful before unmounting a USB stick.

read

Reads a line from the input and stores it in a variable. It is how you ask the user for data in a script.

md5sum

Computes the MD5 hash (128 bits) of one or more files. Used to check that a file has not changed.

sha1sum

Computes the SHA-1 hash (160 bits) of a file. Stronger than MD5, though SHA-256 is preferred today.

sha256sum

Computes the SHA-256 hash (256 bits) of a file. The standard to verify downloads and integrity.

sha512sum

Computes the SHA-512 hash (512 bits) of a file. The longest of the SHA-2 family.

egrep

Like grep but treating the pattern as an extended regular expression. Equivalent to grep -E.

fgrep

Like grep but searching the text literally, without special characters. Equivalent to grep -F.

basename

From a full path, shows only the final name of the file or folder.

dirname

From a full path, shows the folder that contains it (removes the last segment).

readlink

Shows where a symbolic link points. With -f it gives the resolved absolute path.

realpath

Gives the absolute, real path of a file, resolving links and dots.

truncate

Changes a file size: shrinks it or pads it up to the size you ask.

shred

Overwrites a file content before deleting it, so it cannot be recovered.

mkfifo

Creates a named pipe (FIFO): a special file through which two programs exchange data.

shuf

Randomly shuffles lines, values or a range of numbers. Handy for draws and tests.

numfmt

Converts numbers to human-readable form (1M, 2G) or back. Very useful when reading sizes.

strings

Extracts the readable text inside a file, even if it is binary.

yes

Repeats a word endlessly (the letter y by default). Used to answer questions automatically.

lsmod

Lists the kernel modules currently loaded, with their size and who uses them.

modprobe

Loads a kernel module (or unloads it with -r), resolving dependencies.

insmod

Inserts a specific module from its .ko file, without resolving dependencies.

rmmod

Unloads a kernel module. With -f it forces even if in use.

modinfo

Shows information about a module: file, description, license and dependencies.

sysctl

Reads or changes kernel parameters live. With -w it applies them and saves to /etc/sysctl.conf.

loginctl

Shows and manages user sessions and who is logged in (systemd-logind).

resolvectl

Shows and tests name resolution from systemd-resolved. With query it resolves a name.

localectl

Shows or changes the system language and keyboard layout.

systemd-analyze

Measures how long boot takes and which services slow it down. With blame it sorts by time.

logger

Writes a message to the system log (journal), with an optional tag.

nft

Manages the nftables firewall: creates modern rules (replaces iptables).

firewall-cmd

Controls firewalld (the Red Hat/Fedora firewall): ports, services and zones.

getenforce

Shows the current SELinux mode: Enforcing, Permissive or Disabled.

setenforce

Switches SELinux between Enforcing (1) and Permissive (0) live.

semanage

Manages SELinux settings: ports and file contexts.

restorecon

Restores files to their correct SELinux context according to the rules.

chcon

Changes the SELinux context of a specific file (temporary).

openssl

Cryptography Swiss army knife: hashes, random numbers, certificates and passwords.

gpg

Encrypts and decrypts files or messages with GPG. With -c it uses symmetric encryption.

apt-file

Searches which package a file belongs to, even if it is not installed.

add-apt-repository

Adds a repository (PPA) to the APT sources so you can install from it.

dpkg-reconfigure

Reconfigures an already installed package (language, timezone, etc.).

pushd

Saves the current folder on a stack and moves to another. Perfect to go and come back.

popd

Removes the last folder from the stack and moves to it.

dirs

Shows the directory stack you have been saving with pushd.

time

Runs a command and tells you how long it took (real, user and system).

eval

Re-interprets the text you pass it as if you had typed it.

declare

Declares or shows variables (and arrays) with their attributes.

local

Declares a local variable inside a function: it does not leak out.

shift

Shifts a script arguments left: $1 becomes the old $2.

getopts

Walks through a script options (-a, -b value) one at a time.

trap

Schedules an action for when the script exits or receives a signal.

pvcreate

Prepares a disk or partition as a physical volume (PV) to use with LVM.

pvs

Summarizes the physical volumes (PV), their group and size.

pvdisplay

Shows the details of each physical volume: size, extent and group.

pvremove

Removes the LVM label from a physical volume to reuse the disk.

vgcreate

Creates a volume group (VG) grouping one or more PVs.

vgextend

Extends a volume group by adding more physical disks.

vgs

Summary of volume groups: PVs, LVs and size.

vgdisplay

Details of each volume group: size, PE and layout.

lvcreate

Creates a logical volume (LV) inside a group, like a flexible partition.

lvextend

Extends a logical volume without unmounting it or losing data.

lvreduce

Shrinks a logical volume. Careful: it can cut data if the filesystem is not adjusted.

lvremove

Removes a logical volume and frees its space in the group.

lvs

Summary of logical volumes: group, attributes and size.

lvdisplay

Details of each logical volume: path, name, group and size.

mdadm

Creates and manages software RAID: mirror (raid1), parity (raid5), etc.

parted

Creates and examines partitions and partition tables (GPT/MBR).

e2fsck

Checks and repairs ext2/ext3/ext4 filesystems.

tune2fs

Tunes parameters of an ext filesystem and shows its information.

dhcpd

DHCP server: hands out IP addresses automatically to the machines on a network. With -t it only validates the config.

dhclient

DHCP client: asks the server for an address and configures the interface with it.

dhcp-lease-list

Lists the leases handed out by the DHCP server: MAC, IP and hostname.

named-checkconf

Checks that the BIND configuration (named.conf and its includes) is correct. Prints nothing if OK.

named-checkzone

Validates a DNS zone file: checks that it has SOA and NS and that the syntax is correct.

apachectl

Controls and checks Apache. With configtest it validates the config and with -S it lists the virtual hosts.

nginx

Nginx web server. With -t it checks the config and with -s reload it reloads without downtime.

a2ensite

Enables an Apache site (virtual host) by creating the link in sites-enabled.

a2dissite

Disables an Apache site (virtual host) by removing the link from sites-enabled.

testparm

Checks that the Samba configuration (smb.conf) is valid and shows the shared resources.

smbpasswd

Manages Samba user passwords (with -a it adds one).

smbclient

Samba client: lists shares (-L) or connects to a shared folder.

exportfs

Shows or reloads the directories NFS shares (defined in /etc/exports).

showmount

Shows which directories an NFS server is exporting (-e to list them).

postfix

Mail transfer agent (MTA). With check it validates the config and with status it tells if running.

mail

Sends an email from the command line (with -s the subject).

mailq

Shows the system mail queue (messages pending delivery).

sshd

SSH server. With -t it checks the configuration file (/etc/ssh/sshd_config).

lpstat

Shows the status of CUPS printers (the default printer with -d).

lp

Sends a document to the printer (with -d you choose which one).

lpadmin

Administers printers in CUPS: with -p and -v you add a printer and its destination.

nano

Simple text editor in the terminal. Ideal to edit config files without hassle.

vim

Powerful, fast text editor. It has several modes; you learn it with practice.

vi

The classic Unix editor. Almost always vim is its modern version.

more

Shows a file page by page, without scrolling through the text.

clear

Clears the terminal screen leaving the prompt at the top.

exit

Closes the terminal session (or the script you are in).

help

Shows help for the shell built-in commands.

test

Evaluates a condition and returns success or failure. Used in scripts and with [ ].

hostname

Shows or changes the machine name on the network.

lspci

Lists the devices on the PCI bus (cards, controllers...).

lsusb

Lists the devices connected over USB.

lsb_release

Shows the Linux distribution and its version. With -a, all the data.

iostat

Shows disk and CPU input/output statistics.

netstat

Shows network connections, open ports and routing tables (classic).

wall

Sends a message to every terminal of the logged-in users.

apt-get

Classic Debian/Ubuntu tool to install and upgrade packages.

apache2ctl

Debian version of apachectl: checks and controls the Apache server.

unalias

Removes an alias you had defined earlier.

typeset

Like declare: declares variables and their attributes (same as declare).

mkfs

Creates a filesystem on a device (format). With -t you choose the type.

adduser

Creates a new user account. With -m it builds the home folder and copies the base files; it prompts for the rest interactively.

nc

Netcat, the network Swiss army knife: opens TCP/UDP connections, listens on a port and checks whether a port is open. It is invoked as nc or netcat.