Linux and the Command Line reference

177 commands, numbers and terms from the 15 lessons, one line each. The right-hand column opens the page that teaches it.

1What Linux is, and your first commands

DistributionThe Linux kernel plus tools and a package manager: Ubuntu and Debian (apt), RHEL, AlmaLinux and Rocky (dnf)Linux and distributions
cat /etc/os-releaseWhich distribution and version this machine runsLinux and distributions
whoami hostname pwd lsWhich account, which machine, which directory, what is in itFirst commands
Tab / up arrow / Ctrl-C / exitComplete a name / recall a command / stop a command / end the sessionFirst commands
man 5 passwdAsk for a section: 1 commands, 2 system calls, 5 file formats, 8 adminManual pages
man -k wordSearch every manual page's one-line summaryManual pages

2Files and directories

cd dir / cd .. / cd / cd -Into a directory / up one / home / back to the previous oneMoving around
/etc /var /usr /home /tmpSettings, changing data, installed software, users' files, scratchFilesystem hierarchy
/proc /sysNot on disk: the kernel answering as files/proc and /sys
findmnt / df -hTWhich file system is mounted where, and its type and free spaceFilesystem hierarchy
mkdir d cp a b mv a b rm fMake a directory, copy, move or rename, delete (no undo)Copy, move, delete
cp -r / rm -rCopy / delete a directory with everything inside itCopy, move, delete
ls logs/*.logA star matches any characters: list with a pattern before deleting with itCopy, move, delete
mv within one file systemOnly renames: instant whatever the sizeCopy, move, delete
ls -i / stat fileThe inode number, and everything the inode holdsInodes
ln target nameHard link: a second name for the same inode, same file system onlyHard and symbolic links
ln -s target nameSymbolic link: a small file holding a path; breaks if the target movesHard and symbolic links
ls -l first letter- file, d directory, l link, b block device, c character device, s socket, p pipeHard and symbolic links
find / -name '*.conf' -size +1M -mtime -7Walk the tree and test every file by name, size and ageFinding files
find … -exec cmd {} +Run a command on everything foundFinding files
tar -czf a.tgz dir / tar -xzf a.tgzBundle and gzip a folder / unpack it (j for bzip2, J for xz)Archives and compression
tar -tf a.tgzList what is inside before unpackingArchives and compression

3Viewing and editing text

wc -l f / head f / tail fCount lines / first ten / last ten (`-n 5` for five)Viewing files
less fPage through: Space next screen, `/text` search, `n` next match, `G` end, `q` quitViewing files
tail -f fFollow a file and print new lines as they are written; Ctrl-C stopsViewing files
nano: Ctrl-O / Ctrl-X / Ctrl-WSave / leave / searchEditors
vim: Esc :wq / Esc :q!Save and quit / quit without savingText editors
cp -a f f.bak … diff f.bak fCopy before editing, then see exactly what changedChanging settings safely
sshd -t / nginx -t / visudo -cCheck a settings file before the service reloads itChanging settings safely

4Pipes and text tools

0 1 2Standard input, standard output, standard errorStandard streams
> file / >> fileSend output to a file, replacing / appendingRedirection
2> file / 2>&1Send errors to a file / to wherever output goes nowRedirection
cmd > out 2>&1Both streams to one file; order matters, left to rightRedirection
a | ba's output becomes b's input; both run at oncePipes
grep 'text' filePrint the lines that contain the text; `-c` count, `-n` line numbers, `-i` any case, `-v` invertgrep
grep -r text dirSearch every file under a directorygrep
cut -d, -f2 wc -l tr a-z A-Z teeOne column, count lines, translate characters, copy to a file and onText tools
cmd <<EOF … EOFHere-document: a block of lines as inputHere-documents
sort | uniq -c | sort -rn | headCount repeated lines, most common firstPipelines
grep -E 'a|b' fileLines matching a regular expression; -i ignore case, -v invert, -r recurseRegular expressions
^ $ . * [abc]Start, end, any character, repeat, any one ofRegular expressions
sed 's/old/new/g' fileReplace on every line; -i edits the file in placesed
awk -F: '$3 >= 1000 {print $1}' /etc/passwdSplit into fields, filter, print a columnawk

5How the shell works

Expansion orderBraces, tilde, parameters, command substitution, arithmetic, splitting, globsShell expansion
'single' / "double"Single quotes stop every expansion; double quotes keep $ but stop splitting and globsQuoting
name=value / $name / ${name}Set a shell variable (no spaces) / read it / read it where more text followsVariables
$(command)Command substitution: the output of the command, as textVariables
export NAME=valueCopy a variable into every program started from this shellEnvironment variables
envThe environment a program actually receivesEnvironment variables
~/.bashrc / ~/.bash_profileInteractive shells / login shells read these at startStartup files
type lsIs it an alias, a builtin, a function or a file, and which one runsCommand search and PATH
echo "$PATH"The folders searched, left to right; the first match winsCommand search and PATH
echo $?Exit status of the last command: 0 is success, anything else is a failureExit status
cmd1 && cmd2 / cmd1 || cmd2Run the second only if the first succeeded / failedExit status
Ctrl-R / !! / historySearch earlier commands / repeat the last one / list themHistory and aliases
alias ll='ls -alF'A short name for a command; keep it in `~/.bashrc`History and aliases
set -x / echo the lineSee the line after expansion, before it runsLab

6Users, groups and permissions

ls -l file and idThe two sides of every "Permission denied": the file’s owner, group and bits; your user and groupsPermission denied
id userUID, primary group and every group the kernel will checkUsers and groups
/etc/passwd /etc/shadow /etc/groupAccounts; hashes and ageing; group members/etc/shadow
rwxr-x--- = 750r 4, w 2, x 1, for owner, group, othersFile permissions
chmod 640 f / chmod g+w fSet all bits / change oneFile permissions
chmod u+x f / chgrp g f / chown u:g fAdd execute for the owner / change the group / change owner and group (root)chmod, chgrp, chown
Check orderOwner, else group, else others: only one set appliesPermission checks
Directory bitsr list names, w create and delete inside, x enterDirectory permissions
umask 022New files 644, new folders 755Directory permissions
setuid 4, setgid 2, sticky 1Run as owner; inherit folder's group; only owners delete (as /tmp)Directory permissions
chmod 2770 /srv/teamShared team folder: new files keep the team's groupDirectory permissions
setfacl -m u:ana:rw f / getfacl fGive one more user access / read the listDirectory permissions
sudo cmd / visudoOne command as root, logged / edit the rules safelysudo
useradd -m -G team ana passwd ana usermod -aG userdel -rCreate, set a password, add to a group, remove with homeAccount management
chage -M 90 -W 7 anaPassword expires after 90 days, warn 7 days beforeAccount management

7Processes

Process / PIDA running copy of a program / the number that identifies it; `ps` lists, `kill PID` endsPrograms and processes
top keys: P M k rSort by CPU, by memory, kill, renicetop and ps
ps aux --sort=-%cpu | headThe busiest processestop and ps
ps -ef --forest / pstreeEvery process and its parent, back to PID 1Processes
fork then execA copy of the parent, which then loads the new programProcesses
R S D T ZRunning, sleeping, uninterruptible (disk), stopped, zombieProcesses
kill PID / kill -9 PIDSIGTERM 15 asks politely / SIGKILL 9 cannot be caughtSignals
kill -HUP PIDMany daemons reload their settings on SIGHUP 1Signals
Ctrl+Z bg fg jobsStop the foreground job, resume it behind or in front, list jobsJob control
cmd & / nohup cmd &Run in the background / keep running after logoutJob control
uptime / nprocLoad averages for 1, 5 and 15 minutes; compare with the number of CPUsLoad average
nice -n 10 cmd / renice 5 -p PIDStart lower / change later; -20 highest, 19 lowestLoad average
tuned-adm profile virtual-guestApply a set of performance settings (RHEL)Tuning profiles

8Services and start-up

Service (daemon)A program systemd starts at boot, restarts on failure and logs; controlled with `systemctl`Services
systemctl start / enable --nowRun now / run now and at every bootStarting and enabling
systemctl daemon-reloadReread unit files after changing themStarting and enabling
systemctl status unitEnabled, running, last log lines, in one screenService status
journalctl -u unit -p err -b --since '1 hour ago'Filter the journal by unit, priority, boot and timeThe journal
journalctl -fFollow new entries as they arriveThe journal
[Service] ExecStart= Restart=on-failure User=The lines that turn a program into a serviceService units
/etc/systemd/system over /usr/lib/systemd/systemYour units and overrides win over the package'sService units
systemctl edit unitWrite an override without touching the package's fileService units
Wants= vs After=Pull in another unit / only decide the orderService units
Boot orderFirmware, bootloader, kernel, initramfs, systemd as PID 1Boot process
grubby --update-kernel=ALL --args=…Change kernel boot options for good (RHEL)GRUB
systemctl get-default / set-default multi-user.targetWhere boot ends: text or graphicalBoot process
systemctl list-timersEvery timer and when it fires nextScheduled jobs
chronyc tracking / timedatectlIs the clock synchronised, and how far offTime synchronisation

9Installing software

dpkg -L pkg / rpm -ql pkgWhich files a package installedPackages
dpkg -S /path / rpm -qf /pathWhich package owns a filePackages
/etc/apt/sources.list.d/ / /etc/yum.repos.d/Where repositories are listedRepositories
apt-get install --simulate pkgSee the dependency tree before installingDependencies
apt install / dnf installInstall with every dependencyapt and dnf
apt update vs apt upgradeRefresh the index / install newer versionsapt and dnf
apt remove / dnf removeRemove a packageapt and dnf
apt search / dnf search , apt show / dnf infoFind a package, read about itapt and dnf
dnf provides */semanageWhich package would provide a commandapt and dnf
[repo] name= baseurl= enabled=1 gpgcheck=1 gpgkey=A RHEL repository fileapt and dnf
flatpak install flathub appA desktop app with its own runtime, sandboxedapt and dnf
./configure && make && sudo make installBuilding from source: only when there is no packageapt and dnf

10Disks and file systems

lsblk -fDisks, partitions, file systems, UUIDs and mount points as a treeBlock devices
GPT vs MBR128 partitions and any size, with a backup table / 4 primary, 2 TiBBlock devices
parted /dev/sdb mklabel gpt mkpart …Partition a diskAdding storage
mkfs.xfs /dev/sdb1 / mkfs.ext4Make a file systemAdding storage
blkidThe UUID to put in fstabfstab
UUID=… /data xfs defaults 0 0fstab: device, mount point, type, options, dump, fsck orderfstab
mount -a / findmnt --verifyTest fstab before you rebootfstab
pvcreate vgcreate lvcreate -L 10G -n data vgDisks into a pool, volumes out of itLVM
lvextend -r -L +5G /dev/vg/dataGrow the volume and its file system while in useGrowing a volume
xfs_growfs / resize2fsGrow XFS (cannot shrink) / ext4 (can shrink offline)Growing a volume
mkswap swapon free -hMake and enable swap, then check itGrowing a volume
server:/export /mnt nfs defaults 0 0Mount an NFS share at boot; autofs mounts on first useGrowing a volume

11Networking

ip -br a / ip linkAddresses and link state of every interfaceInterfaces
ip route / ip route get 8.8.8.8The routing table / the route one address would takeSubnets and routes
hostnamectl set-hostname web1Set the machine's nameName resolution
/etc/hosts then DNSThe order set in /etc/nsswitch.confName resolution
getent hosts name / dig nameWhat programs will see / what DNS alone saysName resolution
nmcli con mod eth0 ipv4.addresses 10.0.0.5/24 ipv4.gateway 10.0.0.1 ipv4.method manualA fixed address that survives rebootNetworkManager
nmcli con up eth0Apply the profileNetworkManager
ss -tulpnListening TCP and UDP sockets, with the owning processSockets
0.0.0.0 vs 127.0.0.1Listening on every address / only this machineSockets
firewall-cmd --add-service=http --permanent && firewall-cmd --reloadOpen a service for goodfirewalld
firewall-cmd --list-allWhat the active zone allowsfirewalld
Bottom upLink, address, route, name, port, service: stop at the first failureTroubleshooting

12SSH and remote work

ssh user@hostA shell on another machine over an encrypted connection to sshd, TCP port 22Logging in
~/.ssh/known_hostsServer keys you have trusted; a change means a warningKnown hosts
ssh-keygen -t ed25519Make a key pair; the private key never leaves your machineKey pairs
ssh-copy-id user@hostAdd your public key to the server's authorized_keysKey pairs
ssh -v hostPrint every step of the handshakessh -v
Host web HostName User IdentityFileShort names in ~/.ssh/configClient config
rsync -av src/ host:dst/Copy only what changed; trailing slash means the contentsCopying files
scp file host:pathCopy a whole fileCopying files
ssh -L 8080:localhost:80 hostLocal port 8080 reaches port 80 on the serverCopying files
ssh -J jump hostGo through a bastion hostCopying files
PermitRootLogin no PasswordAuthentication no AllowUsersHarden sshd_config, then `sshd -t` and reloadHardening
semanage port -a -t ssh_port_t -p tcp 2222Tell SELinux before moving SSH to another portHardening

13Shell scripts

#!/usr/bin/env bashFirst line: which interpreter runs the fileScripts
chmod +x s.sh && ./s.shMake it runnable, then run itScripts
${var:-default} ${file%.txt} ${#var}Default value, strip a suffix, lengthExpansion
$1 $# "$@" $?First argument, count, all arguments, last exit statusExpansion
"$var" "${arr[@]}"Always quote: keeps values with spaces wholeQuoting
if [[ -f $f ]]; then …; fiTest a file: -f file, -d folder, -z empty stringExit codes and tests
for f in *.log; do …; doneLoop over itemsLoops
while read -r line; do …; done < fileLoop over linesLoops
set -euo pipefailStop on the first error, unset variable or failed pipe stageFailing safely
trap 'echo failed at $LINENO' ERRSay where it failedFailing safely
bash -x s.shShow every command as it really ranFailing safely
shellcheck s.shFind the classic mistakes before runningShellCheck
m h dom mon dow cmdA cron line: minute, hour, day, month, weekdayScheduling
crontab -e / crontab -lEdit / list your cron jobsScheduling

14Troubleshooting a server

uptime free -h df -h ss -tulpn journalctl -p err -bFirst command for load, memory, disk, ports and errorsTriage
journalctl -u nginx --since todayOne unit's log for todayLogs
systemctl status unit then journalctl -u unit -b -eWhy a service failed: the last lines, then everything since bootA service will not start
systemctl reset-failed unitClear the failed state after too many quick restartsA service will not start
du -xh / | sort -h | tailThe biggest folders on one file systemDisk pressure
lsof +L1Deleted files still held open: space df counts but du cannot seeDisk pressure
free -h availableRead available, not free: the cache is given backMemory pressure
journalctl -k | grep -i oomDid the kernel kill a process for memoryMemory pressure
sysctl -w key=value / file in /etc/sysctl.d/Change the kernel now / keep itMemory pressure
lsmod modprobe modLoaded drivers, load oneKernel modules
getenforce / ls -ZSELinux mode / file labelsSELinux
ausearch -m avc -ts recentRead the denialSELinux toolbox
restorecon -Rv path / setsebool -P name onFix a label / turn on a boolean, for goodSELinux toolbox
systemctl rescue / emergencySingle-user repair, with or without file systems mountedRescue and emergency
rd.break at the kernel lineStop in the initramfs to reset the root password (RHEL)Rescue and emergency

NeuroqAI · Linux and the Command Line · neuroqai.com/courses/linux-and-the-command-line/reference/