Source: "Introduction to Linux" course (content developed by the Linux Foundation, video adaptation by Bo K) Audience: Computer users with limited or no prior Linux exposure (individual or enterprise environments) Purpose: A comprehensive, standardized, and detailed reference guide covering all 14 chapters — from Linux distribution families through networking — for study, revision, and real-world reference.
- Chapter 1: Course Introduction & Linux Distribution Families
- Chapter 2: Linux Fundamentals & Terminology
- Chapter 3: File Systems, Partitions, Boot Process & Installation
- Chapter 4: Working with the Graphical Interface
- Chapter 5: System Configuration from the GUI
- Chapter 6: Common Linux Applications
- Chapter 7: The Command Line — Fundamentals, Files & Package Management
- Chapter 8: Getting Help & Documentation
- Chapter 9: Process Management
- Chapter 10: The Linux File System In-Depth
- Chapter 11: Text Editors (Nano, gedit, Vi/Vim, Emacs)
- Chapter 12: Users, Groups, Permissions & Environment
- Chapter 13: Text Processing & File Manipulation Utilities
- Chapter 14: Networking
- Master Command Reference (Cheat Sheet)
- Key Takeaways Summary
This course is designed for users with little to no Linux experience, covering:
- Navigating major Linux distributions, system configurations, and graphical interfaces
- Basic command-line operations
- Common applications used in Linux environments
Conventions used throughout the course:
- A
$at the start of a command line indicates it should be typed into the terminal/shell — the$itself is not part of the command. foois used as generic shorthand (borrowed from the open-source community) to represent "insert a name here" (e.g., a filename or program name) — it does not refer to an actual file or service called "foo."- Extensive built-in documentation exists on every Linux system in the form of man pages (see Chapter 8) — type
man <topic>whenever you need more detail on a command.
Although there are hundreds of Linux distributions ("distros"), this course focuses on three major families:
| Family | Representative Distributions | Package Manager |
|---|---|---|
| Red Hat | RHEL (Red Hat Enterprise Linux), CentOS, CentOS Stream, Fedora, Oracle Linux | RPM-based: YUM / DNF |
| SUSE | openSUSE, SUSE Linux Enterprise (SLE) | RPM-based: Zypper |
| Debian | Debian, Ubuntu, Linux Mint | dpkg-based: APT |
- RHEL (Red Hat Enterprise Linux) heads the family, which includes CentOS, CentOS Stream, Fedora, and Oracle Linux.
- Fedora has a close relationship with RHEL and contains significantly more software than RHEL — built by a diverse community (many contributors don't work for Red Hat) and serves as an upstream testing platform for future RHEL releases.
- CentOS is a close, near-identical clone of RHEL — historically the most popular distro in enterprise environments. Note: CentOS 8 has no more scheduled updates; its replacement is CentOS 8 Stream.
- Oracle Linux is mostly a copy of RHEL with some changes.
- Supports hardware platforms: Intel x86, ARM, Itanium, PowerPC, and IBM System Z.
- Widely used by enterprises that host their own systems.
- The relationship between SUSE Linux Enterprise (SLE) and openSUSE mirrors that of RHEL and Fedora — SLE is upstream from openSUSE.
- openSUSE is used as the reference distribution in this course since it's free for end users; material covering openSUSE largely applies to SLE with minimal differences.
- Uses the RPM-based Zypper package manager.
- Includes YaST (Yet Another Setup Tool) for system administration.
- SLE is widely used in retail and many other sectors.
- Debian is upstream for several distributions, including Ubuntu; Ubuntu, in turn, is upstream for Linux Mint and others.
- Debian is a pure open-source community project — not owned by any corporation — with a strong focus on stability, and it provides by far the largest and most complete software repository of any Linux distribution.
- Ubuntu aims for a good compromise between long-term stability and ease of use; since it draws most packages from Debian's stable branch, it inherits access to that large repository.
- This course uses Ubuntu LTS (Long-Term Support) as the reference distribution for the Debian family.
- Uses the dpkg-based APT (Advanced Package Tool) package manager.
- Ubuntu is widely used for cloud deployments; it is GNOME-based but visually differs from standard Debian's interface under the hood.
- What is the main function of the system?
- What package types matter to the organization (e.g., web server, word processing)?
- How much disk space is required vs. available (especially relevant for embedded devices)?
- How often are packages updated, and what's the support cycle (e.g., LTS = Long-Term Support releases)?
- Do you need kernel customization from a vendor/third party?
- What hardware are you running on (x86, ARM, PPC)?
- Do you need long-term stability, or can you accept a more volatile/cutting-edge system?
Popular free RHEL alternatives: CentOS Stream and similar distros, used by organizations comfortable operating without paid technical support.
Other notes:
- Ubuntu and Fedora are widely used by developers and in education.
- Scientific Linux is favored by the scientific research community for compatibility with scientific/mathematical software.
- CentOS variants are binary compatible with RHEL — binary software packages install properly across these distributions.
- Major commercial distributors (Red Hat, Ubuntu, SUSE, Oracle) provide long-term fee-based support, hardware/software certification, and update services for security/bug fixes and performance enhancements.
| Term | Definition | Examples |
|---|---|---|
| Kernel | The "brain" of the OS — controls hardware and makes it interact with applications | The Linux kernel (see kernel.org) |
| Distribution ("distro") | A collection of programs combined with the Linux kernel to form a complete OS | RHEL, Fedora, Ubuntu, Gentoo |
| Boot Loader | A program that boots the operating system | GRUB, ISOLINUX |
| Service | A program that runs as a background process | httpd, nfsd, ntpd, ftpd, named |
| File System | A method for storing and organizing files | ext3, ext4, FAT, XFS, Btrfs |
| X Window System ("X") | Standard toolkit/protocol for building GUIs on Linux | — |
| Desktop Environment | A graphical user interface layered on top of the OS | GNOME, KDE, Xfce, Fluxbox |
| Command Line | An interface for typing commands directly to the OS | — |
| Shell | The command-line interpreter that executes typed commands | bash, tcsh, zsh |
A full Linux distribution consists of the kernel plus a number of other software tools for:
- File-related operations
- User management
- Software package management
Each tool is often its own separate project with its own developers.
Key facts about the kernel:
- Distributions may be based on different kernel versions — e.g., RHEL 8 is based on the (at the time) not-new but extremely stable 4.18 kernel.
- The kernel is not an all-or-nothing proposition — distributions like RHEL, CentOS, Ubuntu, openSUSE, and SLE often backport newer kernel improvements into older kernel base versions.
Other essential components provided by a distribution:
- C, C++, and other compilers
- The GDB debugger
- Core system libraries applications need to link against
- Low-level graphics interfaces plus higher-level desktop environments
- The package management system for installing/updating components (including the kernel itself)
- A fairly complete suite of pre-installed applications
- Linux borrows heavily from Unix.
- Linux accesses many features/services through files and file-like objects ("everything is a file").
- Linux is a fully multitasking, multi-user OS with built-in networking and background service processes ("daemons").
- Core terms: kernel, distribution, bootloader, service, file system, X Window System, desktop environment, command line.
- A full distribution = kernel + tools for file operations, user management, and package management.
- Power On / POST (Power-On Self-Test): The BIOS (Basic Input Output System, stored on a motherboard ROM chip) initializes hardware (screen, keyboard) and tests main memory.
- Control passes to the Boot Loader: Stored either in the boot sector/MBR (traditional BIOS systems) or the EFI partition (modern UEFI systems). At this stage, no mass storage media has been accessed for the OS itself yet — only CMOS-stored date/time/peripheral info is loaded.
- Boot Loader Stage 1 & 2:
- BIOS/MBR method: The bootloader's first stage resides in the Master Boot Record (MBR) — the first sector of the disk, just 512 bytes. It examines the partition table, finds a bootable partition, and loads the second-stage boot loader (e.g., GRUB) into RAM.
- UEFI/EFI method: UEFI firmware reads boot manager data to determine which UEFI application to launch (e.g., GRUB, defined in the firmware's boot entry). The second-stage boot loader resides under
/boot.
- Boot Loader Menu: A splash screen lets the user choose which OS/kernel to boot.
- Kernel Loading: The boot loader loads the kernel of the selected OS into RAM and passes control to it. The kernel is compressed, so it first uncompresses itself, then checks/initializes hardware and built-in device drivers.
- initramfs (Initial RAM File System): Contains programs/binaries needed to mount the real root file system — including drivers for the needed file system and mass-storage controllers. udev (userspace
/dev) figures out which devices are present, locates their drivers, and loads them. - Root File System Mount: Once found, the root file system is checked for errors and mounted via the
mountprogram, which associates it with a mount point in the file system hierarchy. - init Process: After mounting succeeds, the initramfs is cleared from RAM, and the init program from the real root file system runs — handling the "pivot" to the final root file system. Init then starts all other subsequent processes (except kernel-internal processes, which the kernel starts directly).
- Login prompts: Near the end, init starts text-mode login prompts (or a graphical login manager, if configured), where you can log in and get a shell (usually Bash).
| Boot Loader | Purpose |
|---|---|
| GRUB (GRand Unified Bootloader) | Most common Linux boot loader |
| ISOLINUX | Booting from removable media |
| U-Boot | Booting on embedded devices/appliances |
- Traditional (SysV) init: Dates to 1980s Unix; used sequential runlevels, each running collections of start/stop scripts. Slow, because steps are executed serially.
- systemd (modern standard): Adopted by all major distributions. Faster startup because it uses aggressive parallelization — multiple services start simultaneously. Complicated shell scripts are replaced by simpler configuration files specifying what must happen before/during/after a service starts.
/sbin/initnow simply points to/lib/systemd/systemd.- The primary systemd command-line tool is
systemctl.
- A partition is a physically contiguous section of a disk (or appears to be, in advanced setups).
- A file system is a method of storing/finding files, usually residing within a partition (though it can span multiple partitions using symbolic links, discussed later).
- Analogy: Think of a refrigerator with multiple shelves organizing groceries by type/size — a file system organizes data similarly.
- Linux systems follow the File System Hierarchy Standard, long maintained by the Linux Foundation — this ensures users/admins/developers can move between distributions without relearning organization.
- Linux uses
/(forward slash) to separate paths — unlike Windows' backslash — and has no drive letters; multiple drives/partitions are mounted as directories within a single unified file system tree. - Removable media (USB, CD/DVD) typically mounts at
/run/media/<username>/<label>on modern systems (older systems:/media). - All Linux file systems are case-sensitive —
Boot,boot, andBOOTrepresent three different directories. - Core utilities needed for system operation are separated from other programs, historically placed under
/usr.
- Partition layout is decided at install time and can be difficult to change later (though modifiable via mounting at different points).
- Most installers provide a reasonable default layout: either all space in one big partition + a smaller swap partition, or separate partitions for space-sensitive areas like
/homeand/var. - All installations include a bare-minimum software set; installers typically offer to add categories: common apps (Firefox, LibreOffice), developer tools (vi, emacs), and services (Apache, MySQL).
- Installers set initial security features: root password, an initial user account, and (for graphical systems) a chosen desktop environment.
- Security frameworks: Red Hat-based systems (including Fedora, CentOS) use SELinux by default; Ubuntu comes with AppArmor.
| Distribution Family | Automated Install Config File |
|---|---|
| Red Hat-based | Kickstart file |
| SUSE-based | AutoYaST profile |
| Debian-based | Preseed file |
- Repartition your hard disk to free space for a dual-boot setup alongside your existing OS (complicated — do only when confident).
- Use a hypervisor (e.g., VMware, VirtualBox) to install Linux as a virtual machine (safe).
- Boot from a live CD/USB without writing to the hard disk at all (safe).
- Ubuntu 18.04 (via VMware): The modern Ubuntu installer under VMware requires almost no manual choices — VMware's "Easy Install" auto-detects username/password; the installer partitions automatically (one big ext4 partition + a swap file, not partition), copies files, configures hardware/bootloader (GRUB), and reboots directly into a working system.
- CentOS 8.1: Requires more manual choices — language, keyboard, network (DHCP recommended), time zone (with Network Time enabled), installation source, software selection (Workstation vs. Server), and manual partitioning: a root partition (with a choice of ext4 vs. the RHEL/CentOS default XFS) and a swap partition. Root and user passwords are set, then installation proceeds; the system reboots into the configured system.
- openSUSE (Leap): Similarly guided — language/license, partition proposal (can accept default or edit — e.g., ext4 root + swap), time zone, desktop selection (GNOME/KDE/Server/Custom), and user/root passwords. Installation proceeds via a slideshow/progress screen, then reboots into the new system.
- A partition is a logical part of a disk; a file system stores/organizes files within it.
- Partitioning data allows isolation — if one partition's data is corrupted, others usually survive.
- Boot process: BIOS → Boot Loader → Kernel → initramfs → init → login.
- Choosing a distribution requires matching system needs to distro capabilities.
- The X Window System ("X") is loaded near the end of boot on GUI-based Linux systems.
- A Display Manager service tracks displays and loads the X server (providing graphical services to "X clients"/applications); it also handles graphical logins and starts the desktop environment after login.
- X dates back to the mid-1980s and has known deficiencies (e.g., security) on modern systems.
- Wayland is gradually superseding X and is the default display system for Fedora, RHEL 8, and other recent distributions — it looks like X to the user, but is architecturally different underneath.
A desktop environment consists of:
- Session Manager — starts/maintains graphical session components
- Window Manager — controls window placement, movement, title bars, controls
If a display manager isn't started by default, you can start the graphical desktop from a text console using the startx command.
- GNOME — the default for most distributions, including RHEL, Fedora, CentOS, SUSE Linux Enterprise, Ubuntu, and Debian. Menu-based navigation; look-and-feel varies across distributions despite all running GNOME.
- KDE — historically important, often paired with SUSE/openSUSE.
- Login screens across recent GNOME-based distributions look nearly identical.
- The gear icon on the login screen lets you select alternate desktop sessions (e.g., Wayland vs. various X11 options).
- To log out: click your name in the upper-right corner → Switch User (keeps your session/apps running in the background) or Log Out (fully ends the session).
- Lock screen: Click the lock icon in the upper-right, or use Super+L or Super+Escape (Super = Windows key). Locking does not suspend the computer — apps/processes keep running.
- Background/Wallpaper: Right-click the desktop → "Change Background" → pick a built-in wallpaper, a custom picture, or a solid color.
- GNOME Tweaks (
gnome-tweaks): The default GNOME Settings app is intentionally simplified; GNOME Tweaks exposes many more options (keyboard remapping, themes, extensions, startup applications). Not always installed by default — launch via Alt+F2 and type the command if needed. - Themes: Control the visual appearance of buttons, scrollbars, widgets, etc.
- Opens to your home directory by default; left panel shows common locations (Desktop, Documents, Downloads, Pictures, Computer/root).
- View modes: Icons (Ctrl+1) or List (Ctrl+2); sort by name/size/type/modification date via the View menu.
- Hidden files (dotfiles): toggle visibility with Ctrl+H or "Show Hidden Files."
- Search: Click the search icon, type a keyword — performs a recursive search from the current directory.
- Deleting files: Moves files to
~/.local/share/Trashby default (Ctrl+Deleteor right-click → "Move to Trash"). Permanent deletion:Shift+Delete, or empty the Trash directory.
- Applications are found via the Applications or Activities menu (upper-left corner in GNOME), or via a "Dash" button in some Ubuntu versions; KDE and others use a menu button in the lower-left corner.
- GNOME is a popular desktop environment; its default display manager is GDM.
- Logging out kills all processes in the current X session and returns to the display manager.
- Switching users preserves sessions; suspending puts the computer into sleep mode.
- Every user has a home directory; the file manager offers icon/list/compact views.
- Each distribution ships its own default wallpapers and GNOME themes.
Accessed by clicking the top-right corner icon (gear/tools icon, varies by distro), the Settings panel controls: screen resolution, network connections, date/time, users, and more. Menu layout varies across distributions/versions.
- Configuring resolution/multiple monitors is nearly identical across distributions (Ubuntu, CentOS Stream, openSUSE all shown to have virtually the same "Displays" panel under Settings → Devices → Displays).
- If using a proprietary GPU driver (NVIDIA/AMD), a separate vendor configuration tool may exist — but the built-in Displays panel should be preferred when possible.
- The X server's configuration file is
/etc/X11/xorg.conf— present now mainly only in unusual circumstances (uncommon graphics drivers); direct editing is for advanced users. - Multi-monitor setups are usually auto-configured as one spanning screen; a checkbox enables mirrored mode.
- Linux always uses Coordinated Universal Time (UTC) internally; the displayed/stored local time depends on the system's time zone setting.
- NTP (Network Time Protocol) is the standard/most reliable method for syncing local time via internet time servers — all distributions ship with a working default NTP setup (usually just an on/off toggle needed).
- All Linux distributions have network configuration files, but formats/locations vary — NetworkManager was created to unify and simplify this across distributions.
- Capabilities: lists all available networks (wired/wireless), lets you choose wired/wireless/mobile broadband, handles passwords, sets up VPNs.
- Wired connections: Auto-detected; NetworkManager sets network settings via DHCP by default; static/manual configuration is also possible (address, netmask, gateway, DNS server, routes). You can also change the Ethernet MAC address if supported.
- Wireless connections: View/connect to available networks via the Wi-Fi menu; passwords are saved by default for reconnection.
- Mobile broadband: A setup wizard configures connection details; auto-configures on each subsequent connection.
- VPN support: Native IPsec, Cisco (via client or open-source alternative), Microsoft PPTP, OpenVPN — some VPN types require a separate package from your distributor.
- Every package provides one piece of the system (kernel, compilers, utilities, apps).
- Packages often depend on each other (e.g., an email client using SSL/TLS depends on an encryption package).
- Low-level tool: Handles unpacking a package and placing files correctly (e.g.,
dpkg,rpm) — does NOT auto-resolve dependencies. - High-level tool: Downloads packages, manages dependencies and groups (e.g.,
apt,dnf,yum,zypper).
| Family | Low-Level Tool | High-Level Tool(s) | GUI Examples |
|---|---|---|---|
| Debian | dpkg |
apt |
Ubuntu Software Center, Synaptic, apt-kit |
| Red Hat | rpm |
yum (older) / dnf (newer, Fedora & RHEL 8+) |
GNOME Software, dnfdragora |
| SUSE | rpm |
zypper |
YaST Software Manager |
YaST (Yet Another Setup Tool): openSUSE's graphical software manager — supports installing/removing/updating packages, browsing by RPM group or package group, and searching by name.
GNOME Software / Synaptic (Ubuntu): GNOME Software resembles an app-store interface (browse by category, search, install/remove with a click); Synaptic is an older, more detailed/technical graphical package manager showing dependency information clearly.
- Basic configuration options are controlled through the System Settings panel.
- Linux always uses UTC internally; NTP is the standard time-sync protocol.
- The Displays panel configures resolution and multiple monitors.
- NetworkManager handles wired, wireless, mobile broadband, and VPN connections.
dpkg/aptare used on Debian-family systems;rpmis used by both Red Hat and SUSE families (withyum/dnfandzypperrespectively as high-level tools).
Web Browsers:
- Graphical: Firefox, Google Chrome, Chromium, Epiphany ("Web"), Konqueror, Opera
- Text-based: links, links2, w3m
Email Clients:
- Graphical: Thunderbird, Evolution, Claws Mail
- Text-mode: mutt, mail
- Web-based: Gmail, Yahoo, Office 365 (accessed via browser)
- Most email clients use IMAP (or the older POP/POP3) to access remote mail servers, and can display HTML-formatted emails with embedded images/links.
Other Internet Tools: FileZilla (FTP client), Pidgin, HexChat (IRC/chat clients)
- LibreOffice is the most mature and widely used open-source office suite (evolved from OpenOffice, started 2010), included by default on most distributions.
- Component applications:
| Application | Purpose |
|---|---|
| Writer | Word processing |
| Calc | Spreadsheets |
| Impress | Presentations |
| Draw | Graphics/diagrams |
- LibreOffice can read/write non-native formats (e.g., Microsoft Office formats) — fidelity is generally good, though complex documents may have imperfect conversions.
- Internet-based alternatives: Google Docs, Microsoft Office 365.
- Advanced editors: Vi/Vim, Emacs
- Compilers for virtually every language, including modern ones like Go, Rust
- Debuggers: GDB and various graphical front-ends
- Performance measuring/monitoring tools
- Complete IDEs: Eclipse, Visual Studio Code
- Key advantage over other OSes: These tools are all available at no cost through standard package management, rather than needing separate paid acquisition.
| Category | Applications |
|---|---|
| Sound players | Amarok, Audacity, Rhythmbox (plus streaming via Pandora/Spotify in-browser) |
| Movie/video players | VLC, MPlayer, Xine, Totem |
| Movie editors | Kino, Cinepaint, Blender, Cinelerra, FFmpeg |
| Graphic editors | GIMP (GNU Image Manipulation Program) — full-featured, similar to Adobe Photoshop, handles any image format, plugins/filters, layers/channels/histograms |
| Other graphics utilities | EOG (Eye of GNOME image viewer), Inkscape (vector graphics), ImageMagick's convert, Scribus (desktop publishing) |
- Linux offers a wide range of internet applications: browsers, email clients, and specialized tools like FileZilla, Pidgin, HexChat.
- LibreOffice is the standard document/office suite.
- Development environments include compilers, debuggers, and full IDEs, all freely available.
- Multimedia is well-supported with sound players, movie players/editors, and graphic editors like GIMP.
"Graphical user interfaces make easy tasks easier, while command line interfaces make difficult tasks possible."
Advantages of CLI:
- No GUI overhead
- Virtually any task can be accomplished from the command line
- Scripts can automate repetitive/hard-to-remember procedures
- You can sign into remote machines anywhere on the internet
- You can launch graphical applications directly from the CLI
- The command line interface is consistent across distributions, unlike GUI layouts
A terminal emulator simulates a standalone text terminal in a desktop window.
- GNOME Terminal — default on GNOME desktops
- xterm, Konsole (default on KDE), Terminator — other options
Opening a terminal: Applications → System Tools → Terminal(s); or right-click the desktop → "Open in Terminal"; or Alt+F2 → type gnome-terminal or console.
| Command | Purpose |
|---|---|
cat |
Type out/combine file contents |
head |
Show the first few lines of a file |
tail |
Show the last few lines of a file |
man |
View documentation |
Most command lines have three elements:
- The command — the program name
- Options/switches — modify behavior (usually prefixed with
-or--, e.g.,-por--print) - Arguments — what the command operates on
Some commands take no options, no arguments, or neither.
sudoallows a user to run programs with the security privileges of another user (generally root).- Ubuntu and some other distributions have
sudopre-configured during installation; other distros may require manual setup.
Manual sudo setup (if not already configured):
su # switch to root (will prompt for root password)
# create a config file matching your username under /etc/sudoers.d/
echo "student ALL=(ALL) ALL" > /etc/sudoers.d/student
chmod 440 /etc/sudoers.d/student # some distros require this permission fixBy default, sudo prompts for your own user password (not root's), typically once per session/time window.
- VTs are console sessions using the entire display/keyboard, outside of any graphical environment.
- Only one VT is visible at a time, though multiple can be active.
- One VT (often #1 or #7) is reserved for the graphical environment; text logins run on the unused VTs.
- Ubuntu uses VT7 for graphics; CentOS/RHEL/openSUSE use VT1.
- Switch VTs:
Ctrl+Alt+F<n>(e.g.,Ctrl+Alt+F6for VT6); if already in a VT, justAlt+F<n>suffices. - Use case: Troubleshooting when the graphical desktop malfunctions — switch to a text VT to diagnose.
# systemd-based distros: stop the display manager service
sudo systemctl stop gdm # or lightdm for older Ubuntu (pre-18.04)
sudo systemctl start gdm
# Older-style alternative
sudo telinit 3 # switch to non-graphical mode
sudo telinit 5 # switch to graphical mode- A text terminal prompts with
login:andpassword:— nothing (not even asterisks) is displayed while typing the password, to prevent shoulder-surfing. - Remote login via SSH:
ssh student@remoteserver.com— connects securely, either via password or a cryptographic key. - Shutdown command (preferred method): Sends a warning message, prevents further logins, and lets
initcontrol the actual shutdown/reboot.
sudo shutdown -h now # halt (shutdown) immediately
sudo shutdown -r now # reboot
sudo shutdown -h 10 # halt in 10 minutes
sudo shutdown -h 22:00 "Shutting down for scheduled maintenance" # notify all users- Both shutdown and reboot from the command line require root/sudo access.
- Important: Always shut down properly — improper shutdown risks data loss/corruption.
which diff # find exactly where a program resides
# e.g. /usr/bin/diff
whereis diff # broader search across more system directories if `which` fails| Command | Purpose |
|---|---|
pwd |
Print Working Directory |
cd <dir> |
Change directory |
cd or cd $HOME or cd ~ |
Go to home directory |
cd .. |
Move up one directory level |
cd - |
Return to the previous directory |
pushd <dir> |
Change directory, saving the current one onto a stack |
popd |
Return to the directory at the top of the pushd stack |
dirs |
Display the pushd/popd directory stack |
Example session:
cd /tmp
pwd # /tmp
cd $HOME
pwd # /home/student
cd ..
pwd # /home
pushd /tmp # go to /tmp, remembering /home
popd # back to /home| Path Type | Description | Starts With |
|---|---|---|
| Absolute | Begins at the root directory, follows the tree branch-by-branch to the target | / |
| Relative | Starts from the present working directory | Never starts with / |
- Multiple consecutive slashes are treated as a single slash by the system.
- Shortcuts:
.(current directory),..(parent directory),~(home directory). - Relative paths are usually more convenient (less typing) when the target is nearby.
cd /usr/local/lib # absolute path
cd /usr # back up
cd local/lib # relative path (from /usr)
cd / # go to root directory
ls # list files/directories in current directory
ls -a # include hidden files/directories
tree # tree view of the file system
tree -d / # tree view of directories only, from rootln file1 file2 # create a HARD link — file2 is another name for the SAME inode
ls -li file1 file2 # -i shows inode number — both files share the same inode number
ln -s file1 file3 # create a SYMBOLIC (soft) link
ls -li file1 file3 # file3 shows as a link, pointing to file1, with a DIFFERENT inode numberKey differences:
| Hard Link | Symbolic (Soft) Link |
|---|---|
| Same inode; essentially two names for the same file data | A separate object that just "points to" another file's name/path |
| Deleting one name leaves the underlying data intact under the other name(s) | Deleting the target leaves a dangling link (points nowhere) |
| Cannot cross file systems/partitions | Can cross file systems/partitions/media |
| Takes real disk space (shared with the original) | Takes negligible space (just stores a path) |
| Editing one file usually preserves the link (editor-dependent) — some editors may break it, creating two separate files | More flexible — commonly used to create shortcuts to long paths |
# Viewing files
cat file.txt # print entire file
cat -n file.txt # print with line numbers
less file.txt # page through file, one screen at a time (space = next page)
less -N file.txt # page through with line numbers
head file.txt # first 10 lines (default)
head -20 file.txt # first 20 lines
tail file.txt # last 10 lines (default)
tail -20 file.txt # last 20 lines
tac file.txt # print file in REVERSE line order ("cat" backwards)
# Creating/updating files
touch file.txt # create empty file, or update timestamp if it exists
touch -t <timestamp> file.txt # set a specific timestamp
# Directories
mkdir sample # create a directory
mkdir /usr/sample # create under a specific path
mkdir dir1 dir2 dir3 # create multiple directories at once
rmdir dirname # remove an EMPTY directory (fails if not empty)
rm -rf dirname # remove a directory AND its contents recursively — DANGEROUS, use with caution
# Renaming / moving / removing files
mv file1 newname # rename (or move, if target is a different directory)
rm file # remove a file
rm -i file # remove interactively (prompts for confirmation) — recommended
⚠️ Critical warning aboutrm -rf: This command recursively force-deletes a directory tree with no confirmation. Used carelessly (especially as root), it can wipe out an entire system. Always double- and triple-check the path/pattern before running it.
PS1is the environment variable controlling your command-line prompt appearance.- Special characters (must be in single quotes) let you embed dynamic info like username and hostname — e.g.,
student@localhost:~$. - By convention, the root user's prompt typically ends in
#(pound sign) instead of$.
Every process has three standard streams, represented by file descriptor numbers:
| Stream | File Descriptor Number | Default |
|---|---|---|
| stdin (standard input) | 0 | Keyboard |
| stdout (standard output) | 1 | Terminal |
| stderr (standard error) | 2 | Terminal |
program < inputfile # redirect stdin from a file
program > outputfile # redirect stdout to a file (overwrite)
program >> outputfile # append stdout to a file
program 2> errorfile # redirect stderr to a file (note: no space before 2>)
program > outputfile 2>&1 # redirect BOTH stdout and stderr to the same file (older syntax)
program &> outputfile # shorthand for the same, in bashThe Unix/Linux philosophy favors many small, simple programs cooperating over one large complex program. The pipe (|) connects one command's output directly to another's input:
command1 | command2 | command3- Efficiency benefit: Later commands in the pipeline don't wait for earlier ones to fully finish — they process data as it streams through, better utilizing multi-core systems.
- No temp files needed between stages — saves disk space and avoids slow disk I/O.
locate — searches a pre-built database (fast, but can be stale):
locate lfs101 # search the locate database for "lfs101"
sudo updatedb # manually rebuild the locate database (runs automatically ~daily otherwise)find — searches the live file system in real time (slower, but always accurate, and much more powerful):
find . -name lfs101 # find in current directory tree
find . -iname lfs101 # case-insensitive name search
find . -type d # only directories
find . -type f # only regular files
find . -type l # only symbolic linksRunning commands on found files:
find . -name "*.swp" -exec rm {} \; # remove all .swp files
find . -name "*.swp" -exec rm {} + # alternate valid syntax
find . -name "*.swp" -ok rm {} \; # -ok prompts for confirmation before each executionFinding by time:
find . -ctime -7 # inode/metadata changed in the last 7 days
find . -atime +30 # last accessed more than 30 days ago
find . -mtime 1 # modified exactly 1 day ago
# -amin, -cmin, -mmin: same concepts, but in MINUTES instead of daysFinding by size:
find . -size +10M -exec ls -lh {} \; # files greater than 10 MB
# suffixes: c=bytes, k=KB, M=MB, G=GBWildcards (Globbing):
ls ba?? # ? matches exactly one unknown character
ls *.out # * matches any number of characters
ls [p-z]* # character range: files starting with letters p through z
ls *.??? # matches any 3-character extensionCaution: Quoting a wildcard pattern (e.g.,
apt install "vmware*") prevents the shell from expanding it against local files, instead passing the literal pattern to the program itself — useful when searching a package database rather than local files. Without quotes, the shell tries to expandvmware*against files in the current directory first.
Two levels of tools, in both major families:
| Level | Debian | Red Hat | SUSE |
|---|---|---|---|
| Low-level (unpacks individual packages, no dependency resolution) | dpkg |
rpm |
rpm |
| High-level (resolves dependencies, downloads from repos) | apt / apt-get |
dnf (modern) / yum (legacy, RHEL/CentOS 7 and earlier) |
zypper |
dpkg --list | less # list all installed packages
dpkg --list | grep bzip2 # search for a specific package
dpkg --listfiles bzip2 # list files contained in a package
sudo dpkg --remove bzip2 # remove a package (fails if other packages depend on it)rpm -qa | grep bzip2 # query all installed packages, filter by name
rpm -qil bzip2 # query info + list files for a package
rpm -e bzip2 # erase (remove) a package
rpm -e --test bzip2 # dry-run test of removal (won't actually remove)
rpm -q --whatprovides bzip2 # what package provides this capability
rpm -q --whatrequires bzip2 # what packages depend on this oneapt-cache search wget2 # search for available packages
sudo apt-get install wget2 wget2-dev # install package(s), auto-resolving dependencies
sudo apt-get remove wget2 # remove a package, prompting about dependentsdnf list # list packages (installed shown first)
sudo dnf install lbzip2 bzip2-utils # install with automatic dependency resolution
sudo dnf remove lbzip2 # remove, warns about dependent packageszypper search gnuplot # search for packages
sudo zypper install gnuplot-doc # install (auto-adds dependencies as needed)
rpm -qi gnuplot-doc # get info about the installed package (no sudo needed)
sudo zypper remove gnuplot # remove (with dependent package prompts)- Virtual terminals are text-mode consoles using the full screen/keyboard, outside any GUI.
- Terminal emulator programs emulate a terminal within a desktop window.
- You can log in via a text terminal or remotely via SSH; passwords are never echoed to the screen.
shutdownis the preferred command for halting/rebooting.- Absolute paths start with
/; relative paths start from the current directory. - Hard and soft (symbolic) links are both extremely useful, with different trade-offs.
cd -returns to your previous directory;pushd/popdmanage a directory stack.locateuses a prebuilt database;findsearches live and can execute commands (-exec) on results.touchsets file timestamps or creates empty files.apt(Debian),dnf/yum(Red Hat), andzypper(SUSE) are the primary high-level package managers.
- The oldest and most-used source of Linux documentation — dates back to early 1970s Unix.
- "Man" = manual. Output is piped through a pager (like
less) for easy navigation. - Man pages are organized into numbered chapters/sections (e.g., Chapter 2 = system calls, Chapter 7 = overviews/conventions).
man socket # show the default (usually lowest-numbered) man page for "socket"
man -f socket # list ALL man pages/chapters that exist for "socket" — same as `whatis socket`
man 7 socket # view a SPECIFIC chapter's page (chapter 7 here)
man -a socket # page through ALL matching pages, one after another (press 'q' to move to the next, Ctrl+D to skip)
man -k socket # search all page DESCRIPTIONS for the keyword "socket" — same as `apropos socket`- The GNU Project's preferred alternative documentation format to man pages — free-form and supports hyperlinked subsections (nodes).
- Predates the web but conceptually similar — nodes connect via links.
info make # open the info page for "make" at the top-level ("root") nodeNavigation inside info:
| Key | Action |
|---|---|
/keyword then Enter |
Search for a keyword |
n |
Go to the next node |
p |
Go to the previous node |
u |
Go up one level in the hierarchy |
h |
Show help (available keystrokes) |
q |
Quit |
A node is a documentation section; nodes may contain menus/links to sub-topics (menu items start with * and end with ::).
Most commands support a quick synopsis via:
man --help
command --help # or sometimes: command -hFaster than man/info for a quick reference, but less comprehensive.
Some commands (e.g., echo, cd) are built into bash itself rather than being separate binaries on disk — this is more efficient (faster execution, fewer resources). To see documentation for these built-ins:
help # list all bash built-in commands
help cd # show help for a specific built-in- Desktop help systems (built into GUI applications)
- Package-specific documentation (often under
/usr/share/doc/<package>) - Online resources (project wikis, forums, official docs sites)
- Main documentation sources: man pages, the info system,
--help, and online resources. mansearches, formats, and displays man pages.- The GNU info system supports linked subsections, viewable via CLI, web, or graphical tools.
- Short command descriptions are shown via
-hor--help. helpat the command line lists bash's built-in commands.
A process is an instance of one or more related tasks (threads) executing on the computer — not the same as a program or command (a single command can start several processes simultaneously). Processes consume system resources: memory, CPU cycles, and peripheral devices. The kernel (specifically the scheduler) allocates a fair share of these resources to each process.
| State | Meaning |
|---|---|
| Running | Currently executing on the CPU, or waiting on the run queue for a CPU time slice |
| Sleeping | Waiting for an event (e.g., user input) — sits in a wait queue |
| Zombie | Process has completed, but its parent hasn't yet acknowledged/read its exit status — the process "isn't really alive" but still appears in the process list |
- Every running process gets a unique numerical PID.
- PIDs are generally assigned in ascending order — PID 1 is always the
initprocess; successive processes get higher numbers.
kill -SIGKILL <PID> # forcefully terminate a process
kill -9 <PID> # same effect, using the signal number directlyYou can only kill your own processes unless you're root.
| ID | Meaning |
|---|---|
| RUID (Real User ID) | The user who started the process |
| EUID (Effective User ID) | Determines the process's access rights — may differ from RUID |
| RGID (Real Group ID) | The group the starting user belongs to |
| EGID (Effective Group ID) | Determines the process's group-based access rights |
- Nice value ranges from -20 (highest priority) to +19 (lowest priority) — counterintuitive, but this is a Unix convention dating back decades.
- A higher nice value means the process "allows others to go first" (lower priority).
- Only root can decrease a process's nice value (i.e., increase its priority); any user can increase their own process's nice value (lower its priority).
ps -lf # view PID and NI (nice) columns
renice +5 <PID> # lower the priority (raise the nice value) — any user can do this to their own processes
sudo renice -5 <PID> # raise the priority (lower the nice value) — requires rootThis can also be done graphically via GNOME System Monitor → right-click a process → "Change Priority."
- The load average reflects processes that are: actively running, runnable-but-waiting for CPU, or sleeping (waiting on a resource).
- Displayed as three numbers (1-min, 5-min, 15-min averages) via
w,top, oruptime.
Interpreting load average (single-CPU example):
| Value | Meaning |
|---|---|
0.45 |
System was 45% utilized (average, over that time window) |
1.0 |
System was 100% utilized (fully loaded, but not overloaded) — good if trying to maximize usage |
> 1.0 |
System was overutilized — more processes needed the CPU than were available |
For multi-core systems, divide by the number of CPUs — e.g., a load average of 4.0 on a quad-core system means 100% average utilization.
Short-term spikes (e.g., during startup) are usually not concerning; sustained high 5/15-minute averages may warrant investigation.
- A job is a command launched from a terminal window.
- Foreground jobs run directly, blocking further shell use in that terminal until they complete.
- Background jobs free the shell for other tasks, running at a slightly lower priority.
updatedb & # run a command in the BACKGROUND (& at the end)
# Ctrl+Z suspend a running foreground job
# Ctrl+C terminate a running foreground job
bg # resume a suspended job IN THE BACKGROUND
fg # bring a background/suspended job back to the FOREGROUND
jobs # list background jobs (shows Job ID, state, command)
jobs -l # same, plus PIDsBackground jobs are tied to the terminal window that started them — closing that terminal typically ends the job (unless detached via tools like
nohup,disown, orscreen/tmux).
ps # processes running under the CURRENT shell only
ps -f # "full" format — adds Parent PID (PPID), etc.
ps -l # "long" format — adds priority (PRI) and niceness (NI) columns
ps -ef # ALL processes on the system, full detail
ps -eLf # like -ef, but one line PER THREAD (a process may have multiple threads)
ps -u <username> # processes for a specific user
ps aux # BSD-style syntax (no leading dash) — shows %CPU, %MEM, etc.
ps axo <fields> # custom output — choose exactly which columns to display
ps fax # tree-style view of process/parent relationships (like `pstree`)Kernel-internal processes (not started by a user program) appear with square brackets, e.g.,
[kworker/0:1], inps -efoutput — these manage internal OS tasks.
Displays processes as a tree diagram showing parent-child relationships; repeated entries are collapsed, and threads shown in curly braces.
top # launch; press 'q' to quitTop's output header explained:
| Line | Contents |
|---|---|
| Line 1 | Uptime, number of logged-in users, load average (1/5/15 min) |
| Line 2 | Total tasks, and how many are running/sleeping/stopped/zombie |
| Line 3 | CPU time breakdown: us (user), sy (system/kernel), ni (niced processes), id (idle), wa (waiting for I/O), hi/si (hardware/software interrupts), st (steal time — relevant on VMs) |
| Line 4 | Physical memory (RAM) usage: total/used/free |
| Line 5 | Swap space usage: total/used/free |
Per-process columns: PID, user, priority (PR), nice value (NI), virtual/physical/shared memory, state (S), %CPU, %MEM, execution TIME+, and COMMAND. Sorted by CPU usage by default.
Interactive keys within top:
| Key | Action |
|---|---|
1 |
Show per-CPU statistics (instead of an aggregate total) |
h |
Show help / available keystrokes |
q |
Quit |
| (others) | Change process priority, kill/stop processes, change sort order, etc. — see h for full list |
Graphical equivalent: GNOME System Monitor — click column headers to sort (e.g., by Memory or CPU), right-click to change priority or kill a process; also shows live resource graphs and file system usage.
at — run a one-time, non-interactive command at a specified future time:
at 5:00pm tomorrow
at> your-command-here
at> <Ctrl+D>cron — time-based scheduling for recurring background jobs, driven by a crontab file:
crontab -e # edit your personal crontab (opens an editor)Each crontab line has 6 fields: minute hour day-of-month month day-of-week command.
sleep — suspends execution for a specified duration, then resumes automatically:
sleep 10 # sleep 10 seconds (default unit)
sleep 5m # 5 minutes
sleep 2h # 2 hours
sleep 1d # 1 dayKey distinction:
sleepdelays the execution of the current command/script for a fixed period;atschedules a command to run once at a specific future time.
- Processes perform tasks; they can be single- or multi-threaded, and interactive or non-interactive.
- Every process has a unique PID.
- The nice value sets priority (-20 highest, +19 lowest).
psgives a point-in-time snapshot;topgives continuously refreshing real-time data.- Load average indicates system utilization over 1/5/15-minute windows.
- Background/foreground job control lets you manage long-running tasks without blocking the shell.
atruns a one-time future task;cronhandles recurring scheduled tasks.
On Unix-like systems, normal data files, documents, and even devices (sound cards, printers) are accessed through the same kind of I/O operations — you open, read, and write. This uniformity is a cornerstone of Unix/Linux design.
- Structured like an inverted tree, starting at the root directory (
/, also called "the trunk"). - The root directory is not the same as the root user's home directory (which is also
/root, by convention, on modern systems).
Native Linux file systems: ext3, ext4, XFS, Btrfs, SquashFS, and more; Linux also supports many "foreign" file system formats (from Windows, macOS, SGI, IBM) and legacy ones like FAT.
- Each file system typically occupies its own disk partition.
- Common partition strategy: separate partitions for critical system files (
/or "root"), user files (/home), and volatile/variable data (/var) — this isolates failure domains; if one partition fills up, the system may still operate normally. - Mounting: Before use, a file system must be mounted at a mount point — a directory in the file system tree.
⚠️ Mounting onto a non-empty directory hides its existing contents until unmounted — mount points should generally be empty directories.
sudo mount /dev/sda5 /home # mount a partition at a mount point
sudo umount /home # unmount (note: "umount", not "unmount"!)
mount # show all currently mounted file systems
df -Th # disk free — shows file system type + usage stats, human-readable sizes- To make a mount persistent across reboots, edit
/etc/fstab(seeman fstabfor the format).
Allow sharing data across physical machines/locations:
- NFS (Network File System) — the most common, long history, originally developed by Sun Microsystems.
- CIFS/Samba — has Microsoft roots, for Windows-compatible file sharing.
A common use case: mounting remote users' home directories on a server so they get consistent access across multiple client machines.
| Directory | Purpose |
|---|---|
/home |
Home directories for regular users (e.g., /home/student); can be its own partition or even NFS-mounted |
/root |
The root (superuser) account's home directory — NOT the same as / |
/bin, /sbin |
Essential executable binaries needed to boot/operate the system (/bin: general use like cat, cp, ls; /sbin: admin-related, like fsck, ip) |
/usr/bin, /usr/sbin |
Non-essential (not needed for single-user boot mode) binaries — historically separated so /usr could be mounted later/remotely; on modern distros, /bin→/usr/bin and /sbin→/usr/sbin are just symbolic links |
/proc |
A pseudo file system — virtual files that exist only in memory, exposing live kernel/process data (no permanent disk presence); e.g., /proc/<PID>/ per running process, /proc/cpuinfo, /proc/meminfo |
/dev |
Device nodes (pseudo files representing hardware/software devices), e.g., /dev/sda1 (first partition on first disk), /dev/lp1 (second printer), /dev/random. Populated dynamically by udev. |
/var |
Variable data expected to change in size/content: log files (/var/log), package/database files, print queues (/var/spool), temp files (/var/tmp). Often its own partition to contain growth. Also hosts network service directories like /var/ftp, /var/www. |
/etc |
Systemwide configuration files (no binaries) — e.g., /etc/resolv.conf (DNS config), /etc/passwd, /etc/shadow, /etc/group. Only root can modify. User-specific configs live under the user's home directory instead. |
/boot |
Files needed to boot the system: vmlinuz (compressed kernel), initramfs (initial RAM file system), config (kernel build config, for debugging), System.map (kernel symbol table). GRUB config files also live here (e.g., /boot/grub2/grub.cfg). |
/lib, /lib64 |
Shared libraries (common code needed by essential programs in /bin and /sbin); on modern distros these too are often just symlinks to /usr/lib |
/lib/modules/<kernel-version> |
Loadable kernel modules (often device drivers) |
/run |
Modern mount point location for removable media (e.g., /run/media/student/MyUSBDrive) — historically this was under /media |
/mnt |
Traditional, general-purpose location for temporarily mounting file systems (removable media, network shares, loopback files) |
/usr |
Theoretically non-essential programs/scripts (not needed to initially boot); contains its own subdirectory structure (bin, sbin, lib, share, etc.) |
diff — compares two text files, showing differences:
diff options file1 file2diff3 — compares three files at once, using one as a common reference basis (useful when two people independently modify the same original file):
diff3 mine original yourscmp — for comparing binary files (diff is meant for text).
- Patches distribute source code/config changes efficiently — a patch file contains only the deltas (differences), not the whole file.
- Patch files are generated by running
diffwith the correct options.
diff -Naur oldfile newfile > mychanges.patch # create a patch
patch < mychanges.patch # apply to a single file
patch -p1 < mychanges.patch # apply across a directory tree (common usage)Unlike Windows (where .exe = executable), Linux file names are largely cosmetic/meaningful to the user only — a file named file.txt isn't necessarily a text file. Most applications examine the file's actual content, not its name/extension, to determine its type.
file somefile # examines content, reports the real type: plain text, executable, script, shared library, etc.cp |
rsync |
|---|---|
| Simple local copy (source/destination on the same machine) | Can synchronize across remote machines too |
| Always re-copies fully | Skips files that already match (size/mtime unchanged) — saves time |
| Copies the whole file even for small changes | Copies only the changed parts of a file — very fast for large, mostly-unchanged files |
rsync -avz source/ user@remotehost:/path/to/destination/ # common combination of options
rsync --dry-run -av source/ destination/ # TEST what would happen, without actually copying — highly recommended before a real run
⚠️ Caution:rsynccan be destructive — accidental misuse (wrong direction, wrong flags) can overwrite/delete data. Always test with--dry-runfirst.
Common Linux compression methods (trade-off between compression ratio and speed — better compression generally takes longer; decompression speed varies less):
- gzip (
.gz) - bzip2 (
.bz2) - xz (
.xz) - zip (
.zip)
- The file system tree starts at the root directory (
/). - The FHS gives Linux developers/admins a standard directory layout.
- Partitions segregate files by usage, ownership, and type.
- File systems mount anywhere on the tree at a mount point;
/etc/fstabautomates mounting at boot. - NFS is a common way to share files/data across a network.
/procis a pseudo file system existing only in memory./rootis the root user's home directory;/varoften gets its own partition;/bootholds essential boot files.patchapplies deltas generated bydiffto update files.- File extensions in Linux do NOT reliably indicate file type — use
fileinstead. cpcopies locally;rsyncsynchronizes efficiently, including across machines.
Word processors (LibreOffice Writer, etc.) embed hidden formatting that will corrupt config files/scripts — always use a plain text editor for system administration, scripting, and source code.
echo "some text" > file.txt # single > OVERWRITES / creates
echo "more text" >> file.txt # double >> APPENDS
cat > file.txt << EOF
line one
line two
line three
EOFUseful especially inside scripts.
nano file.txt # opens (or creates) the file; on-screen shortcut hints shown at the bottom| Shortcut | Action |
|---|---|
Ctrl+G |
Display help |
Ctrl+O |
Write (save) file |
Ctrl+X |
Exit |
Ctrl+R |
Insert contents of another file |
Ctrl+C |
Show cursor position |
- Part of the GNOME desktop system (KDE's equivalent is Kate/KWrite).
- Visually similar to Windows Notepad, but far more capable and configurable with many available plugins.
- Launch from the menu, or
gedit filenamefrom the terminal.
- Vim ("Vi IMproved") is the version installed on virtually all modern distributions, aliased to
vi. - Even if you prefer another editor, familiarity with Vi is essential — it's guaranteed to be present on virtually every Linux/Unix/macOS system, and sometimes it's the only editor available.
- Graphical variants: gVim (GNOME), KVim (KDE).
- All commands are keyboard-driven — no mouse required.
- Learn interactively: run
vimtutor— a short, comprehensive 7-lesson tutorial.
Vi's Three Modes:
| Mode | Purpose |
|---|---|
| Command mode | Default mode on opening; keystrokes are interpreted as commands (navigation, deletion, etc.) |
| Insert mode | Actual text typing/editing (enter via i, a, o, etc.) |
| Line (ex/colon) mode | Commands prefixed with :, require pressing Enter (e.g., saving, quitting, search-and-replace) |
Starting/Exiting/Saving:
vi filename # open a file in command mode| Key(s) | Action |
|---|---|
i |
Enter insert mode (before cursor) |
a |
Enter insert mode (after cursor) |
Esc |
Return to command mode |
:wq then Enter |
Write (save) and quit |
:q |
Quit (only if no unsaved changes) |
:q! |
Quit WITHOUT saving changes |
:w |
Write (save) without quitting |
Cursor Movement (Command Mode):
| Key | Movement |
|---|---|
h |
Left one character |
j |
Down one line |
k |
Up one line |
l |
Right one character |
w |
Move to the beginning of the next word |
$ |
Move to the end of the current line |
0 |
Move to the beginning of the current line |
Editing Commands:
| Key | Action |
|---|---|
x |
Delete character under cursor |
dd |
Delete (cut) the current line |
yy |
Yank (copy) the current line |
p |
Paste after cursor/line |
u |
Undo |
/pattern + Enter |
Search forward for a pattern |
n |
Repeat the last search (next match) |
External commands from within Vi:
:sh # open an external shell (exit it to return to vi)
:! wc % # run a command on the current file (% represents the current buffer's file); good for non-interactive commands
- Does not use modes like Vi — instead relies heavily on Ctrl and Meta (Alt/Escape) key combinations for all commands.
- Highly customizable, with a huge feature set beyond text editing (email, debugging, and more).
- Built-in interactive tutorial:
Ctrl+Hthent(from within Emacs).
Common Emacs commands:
| Key Combo | Action |
|---|---|
Ctrl+X Ctrl+F |
Open (find) a file |
Ctrl+X Ctrl+S |
Save file |
Ctrl+X Ctrl+C |
Exit Emacs |
Ctrl+S |
Incremental search forward |
Ctrl+A |
Move to beginning of line |
Ctrl+K |
Kill (cut) to end of line |
Ctrl+Space then move cursor, then Ctrl+W |
Select a region and cut ("kill") it |
Ctrl+Y |
Yank (paste) previously killed text |
Esc % |
Query-replace (prompts per match; ! replaces all remaining automatically) |
Ctrl+X 2 |
Split window horizontally |
Ctrl+X O |
Switch to the "other" window |
Ctrl+X 1 |
Return to a single window |
Ctrl+X B |
Switch buffers |
A well-known quirk: many veteran Emacs users remap Caps Lock to act as an additional Control key, since the default Control key placement is awkward for the heavy Ctrl-combo usage Emacs requires.
- Text editors (not word processors) are essential for config files, scripts, and source code.
- Nano — easy, text-based, with on-screen prompts.
- gedit — a graphical Notepad-like editor.
- Vi/Vim — universally available, has three modes (command, insert, line), steep learning curve but extremely efficient once mastered.
vimtutorteaches the basics. - Emacs — a popular Vi alternative with a single mode, relying on Ctrl/Meta key combos; supports GUI and text interfaces.
Ctrl+H tlaunches its tutorial.
whoami # print the current username
who # list all currently logged-in users
who -a # more detailed information| File | Scope |
|---|---|
/etc/profile |
Global settings for ALL users, read first at login |
~/.bash_profile, ~/.bash_login, ~/.profile |
Per-user login shell config — checked in this order; the first one found is used, and the rest are ignored |
~/.bashrc |
Read every time a new shell/terminal is opened (not just at login) — most user customizations (aliases, functions) go here |
Startup files can customize the prompt, define aliases/shortcuts, set the default editor, and set the
PATH.
alias ll='ls -la' # define a custom alias (no spaces around =; quote if it contains spaces)
alias # list all currently defined aliases
unalias ll # remove an aliasMost often placed in ~/.bashrc so they're available in every new shell.
- Every user has a unique UID — normal (non-system) users typically start at UID 1000 or higher.
- Groups organize accounts sharing certain permissions; managed via
/etc/group. - Every user has a primary/default group, plus optionally additional groups.
- User info is stored in
/etc/passwd; group info in/etc/group.
sudo useradd -m -c "Eric Dolphy" -s /bin/bash edolphy # create a user: -m makes a home dir, -c sets full name (comment), -s sets shell
sudo passwd edolphy # set the user's password
sudo userdel edolphy # delete a user account (leaves home directory intact)
sudo userdel -r edolphy # delete a user AND remove their home directory
id # show UID/GID info for the CURRENT user
id edolphy # show UID/GID info for another user
sudo groupadd newgroup # create a new group
sudo groupdel newgroup # delete a group
sudo usermod -a -G newgroup rjsquirrel # ADD a user to an additional group (-a = append; ALWAYS use -a here!)
groups rjsquirrel # show a user's group memberships
sudo usermod -G group1,group2 rjsquirrel # ⚠️ WITHOUT -a: REPLACES the user's supplementary group list entirely
sudo groupmod -g <newGID> groupname # change a group's GID
sudo groupmod -n <newname> groupname # rename a groupCritical distinction:
usermod -a -Gappends a group;usermod -G(without-a) overwrites the entire supplementary group list — a very common and dangerous mistake if-ais forgotten.
- The root account has full, unrestricted access — equivalent to "Administrator" on other OSes.
- Granting full root access to a regular user is rarely justified and is a common attack vector once compromised.
su— switches to another user's shell (usually root), requiring that user's password:
su # become root (prompts for ROOT's password)sudo— runs a single command with elevated privileges, prompting for your own password:
sudo <command>Best practice: Prefer
sudooversu— it's more auditable, limits the scope/duration of elevated access, and reduces the risk of accidentally causing damage while "living" in a root shell.
sudoconfiguration lives in/etc/sudoersand/etc/sudoers.d/(usually empty by default, with per-user files added as needed — edit/etc/sudoersonly viavisudo, never directly).
env # list currently exported environment variables
export # (with no args) also lists exported variables
set # lists ALL shell variables (typically far more output than env/export)
export MYVAR=value # define AND export a variable so child processes/subshells can see it
VAR1=a VAR2=b make install # set variables for a SINGLE command only (temporary, "one-shot")Variables set in a script are, by default, only visible to the current shell — child processes (subshells) won't see them unless explicitly
exported.
Key built-in environment variables:
| Variable | Purpose |
|---|---|
HOME |
The user's home/login directory (cd with no args, or cd ~, goes here) |
PATH |
A colon-separated ordered list of directories searched for executable programs |
SHELL |
Full path to the user's default shell program |
PS1 |
Controls the command-line prompt's appearance |
export PATH=$PATH:~/bin # prefix/append a private directory to your existing PATHhistory # display command history list
history 20 # show last 20 commands
!156 # re-run command number 156 from history
!! # re-run the LAST command
Ctrl+R # reverse incremental search through history (type to search, press Ctrl+R again for older matches)- Stored (by default) in
~/.bash_history, but only written when the shell session terminates; multiple concurrently open terminals don't share history live. - Related variables:
HISTFILE,HISTFILESIZE(max lines in the file, default 500),HISTSIZE(max commands in memory),HISTCONTROL,HISTIGNORE.
| Shortcut | Action |
|---|---|
Ctrl+A |
Move cursor to beginning of line |
Ctrl+E |
Move cursor to end of line |
Ctrl+U |
Delete from cursor to beginning of line |
Ctrl+K |
Delete from cursor to end of line |
Ctrl+W |
Delete the word before the cursor |
Ctrl+L |
Clear the screen |
Ctrl+C |
Kill/interrupt the current command |
Ctrl+D |
Log out / signal end-of-input (EOF) |
Tab |
Auto-complete commands/filenames |
Case doesn't matter for these —
Ctrl+AandCtrl+Shift+Abehave the same.
Every file has an owning user, an owning group, and three permission categories: read (r), write (w), execute (x) — applied to three scopes: owner (user), group, and others (world).
ls -l file.txt
# -rwxr-xr-- 1 student staff 4096 Jan 1 10:00 file.txt
# \_/\_/\_/
# | | └─ others: r-- (read only)
# | └──── group: r-x (read + execute)
# └─────── owner: rwx (read + write + execute)Changing permissions with chmod — symbolic method:
chmod u+x,g-w,o+x file.txt # u=owner/user, g=group, o=others; + adds, - removesChanging permissions with chmod — numeric (octal) method:
Each permission has a numeric value: read = 4, write = 2, execute = 1 — sum them per scope.
| Digit | Meaning |
|---|---|
7 |
rwx (read+write+execute) |
6 |
rw- (read+write) |
5 |
r-x (read+execute) |
4 |
r-- (read only) |
0 |
--- (no permissions) |
chmod 755 script.sh # owner: rwx (7), group: r-x (5), others: r-x (5) — typical for an executable script
chmod 644 file.txt # owner: rw- (6), group: r-- (4), others: r-- (4) — typical for a data fileChanging ownership:
sudo chown newowner file.txt # change owning user
sudo chown newowner:newgroup file.txt # change owning user AND group simultaneously
sudo chgrp newgroup file.txt # change owning group only- Linux is a multi-user system;
who/whoamiidentify current session(s). sudois preferred oversufor temporary elevated privileges.- Shell startup files (
/etc/profile,~/.bash_profile,~/.bashrc) build the user environment;~/.bashrcruns on every new shell. - Environment variables are strings used by the shell/applications;
exportmakes them visible to child processes. historyrecalls past commands; many editing keyboard shortcuts speed up command-line work.- Aliases customize/simplify commands, typically defined in
~/.bashrc. - File permissions (
chmod) and ownership (chown/chgrp) control access at the owner/group/other level.
cat file.txt # display file contents
cat file1.txt file2.txt # concatenate/display multiple files together
cat file1.txt file2.txt > file3.txt # combine into a new file
cat > newfile.txt << EOF # create a file interactively (heredoc)
some text
EOFtac (cat spelled backward) prints a file's lines in reverse order.
less somefile.log # or: cat somefile.log | less — page through without loading the WHOLE file into memory (unlike a text editor)
head -5 /etc/default/grub # first 5 lines
tail -15 somefile.log # last 15 lines
tail -f somefile.log # "follow" mode — continuously show NEW lines as they're appended (ideal for live log monitoring)
manpages themselves are piped throughlessby default. The oldermoreutility is largely superseded (lessis more capable — hence the joke, "less is more").
One of the oldest, most powerful Unix text-processing tools — applies editing operations to an input stream/file and outputs the result (leaving the original file unchanged unless explicitly told otherwise).
sed -e 's/pattern/replacement/' file.txt # replace FIRST occurrence per line
sed -e 's/pattern/replacement/g' file.txt # replace ALL occurrences (g = global) per line
sed -e '1,2s/pattern/replacement/' file.txt # apply only to lines 1-2
sed 's:pattern:replacement:' file.txt # any delimiter can replace the traditional "/" (useful if your pattern contains slashes)
sed -e 's/pattern/replacement/g' infile.txt > outfile.txt # write results to a NEW file (safer than in-place editing)
sedsupports full regular expressions, enabling powerful pattern-based substitutions.
Created at Bell Labs in the 1970s (name derived from its authors' surnames: Aho, Weinberger, Kernighan). It's both a text-extraction tool and a lightweight interpreted programming language, ideal for working with fields (columns) and records (lines).
awk '{print $1}' file.txt # print the first field/column of each line (default delimiter: whitespace)
awk -F: '{print $1}' /etc/passwd # -F sets a custom field separator (colon, for /etc/passwd)
awk -f script.awk file.txt # run a more complex script from a filesort file.txt # sort lines, ascending, by default (ASCII/alphabetical order)
sort -r file.txt # reverse (descending) order
sort -u file.txt # unique values only, after sorting (equivalent to sort | uniq)
sort file.txt | uniq # remove duplicate CONSECUTIVE lines (uniq requires pre-sorted input to catch all dupes)
sort file1 file2 file3 -u > combined.txt # merge multiple files, sorted, deduplicated
uniq -c file.txt # count occurrences of each duplicate linepaste — merges corresponding lines from multiple files side-by-side (columns):
paste file1.txt file2.txt # combine columns, tab-delimited by default
paste -d, file1.txt file2.txt # use a custom delimiter (e.g., comma)
paste -s file1.txt # append lines in series (horizontal) rather than parallel (vertical)join — like an enhanced paste; merges lines from two files based on a common field (like an SQL join):
join file1.txt file2.txt # join on the first common field by defaultBreaks a large file into equal-sized segments (useful for viewing/transferring huge files):
split infile # default: 1000-line segments, output files named "xaa", "xab", etc.
split infile myprefix # custom prefix instead of "x"
wc -l dictionary # (word count utility) — check total line count first, e.g., 999,999 lines
split -n 100 dictionary dict_ # split into ~100 equal segments with a custom prefix| Pattern | Matches |
|---|---|
^word |
Lines starting with "word" |
word$ |
Lines ending with "word" |
. |
Any single character |
* |
Zero or more of the preceding character |
[abc] |
Any one character in the set (a, b, or c) |
[^abc] |
Any character NOT in the set |
[a-z] |
Any character in the range |
Regular expressions are used extensively by vi, sed, awk, find, and grep.
grep "pattern" file.txt # basic search, print matching lines
grep -i "pattern" file.txt # case-insensitive search
grep -r "pattern" directory/ # recursive search through a directory tree
grep -v "pattern" file.txt # invert match — show lines NOT matching
grep -n "pattern" file.txt # show line numbers alongside matches
grep -c "pattern" file.txt # count matching lines instead of printing them
grep -E "pattern1|pattern2" file.txt # extended regex (alternation, etc.)Extracts all printable character strings found in a file — very useful for finding human-readable content embedded inside binary files:
strings /path/to/binary_file | grep "mycompany"cat city.txt | tr 'a-z' 'A-Z' # translate all lowercase to uppercase
tr -d '0-9' < file.txt # delete all digit charactersRequires exactly two sets (a max of two arguments): the characters to find, and the characters to substitute (or omit the second set with
-dto just delete matches).
ls -l | tee newfile.txt # display output on screen AND simultaneously save it to a file
cat newfile.txt # confirm the saved contentwc file.txt # shows: lines, words, characters (all three, by default)
wc -l file.txt # lines only
wc -w file.txt # words only
wc -c file.txt # characters/bytes onlyls -l | cut -d " " -f3 # -d sets the delimiter (space here), -f selects the field number
cut -d: -f1 /etc/passwd # extract just usernames from /etc/passwd (colon-delimited)- The command line is often more efficient than the GUI for text/file manipulation.
catreads/prints/combines files;echowrites text to output or a file.sedis a powerful stream editor for filtering and substituting text.awkis an interpreted language for data extraction and reporting, working with fields and records.sort,uniq,paste,join, andsplitprovide various file-combination and organization utilities.- Regular expressions enable pattern matching for start/end-of-line, wildcards, and character sets.
grepsearches files/streams for patterns (supports regex).trtranslates characters;teeduplicates output to screen and file;wccounts lines/words/characters;cutextracts specific columns.less,head, andtailare essential for viewing large files without loading them entirely into memory.stringsextracts printable text from binary files.
A network connects computers/devices via cables or wireless media, allowing them to: communicate, share resources (printers, media servers), and exchange information. The internet is the largest network — the "network of networks."
- Every networked device needs at least one unique IP (Internet Protocol) address for routing.
- Data travels as packets, each containing a data buffer plus headers (source, destination, sequence info).
| IPv4 | IPv6 | |
|---|---|---|
| Address size | 32 bits | 128 bits |
| Total addresses | ~4.3 billion | ~3.4 × 10³⁸ |
| Status | Older, far more widely used | Newer, designed to overcome IPv4's exhaustion |
| Adoption challenges | — | The two protocols don't always interoperate well; migration requires significant effort |
NAT (Network Address Translation) helps stretch IPv4's limited address space by letting many locally-connected devices share one externally visible IP address, each getting a unique local address (common in home routers).
A 32-bit IPv4 address is divided into four 8-bit octets (e.g., 192.168.1.1).
Address Classes:
| Class | First Octet Range | Net ID / Host ID Split | Max Networks | Max Hosts per Network |
|---|---|---|---|---|
| Class A | 1–126 | 1 octet net ID / 3 octets host ID | 126 | ~16.7 million |
| Class B | 128–191 | 2 octets net ID / 2 octets host ID | 16,384 | 65,536 |
| Class C | 192–223 | 3 octets net ID / 1 octet host ID | ~2.1 million | 256 |
| Class D | — | Reserved for multicast | — | — |
| Class E | — | Reserved for future use | — | — |
- Manual/Static: A fixed address that never changes.
- Dynamic: Assigned via DHCP (Dynamic Host Configuration Protocol), which may change on each reboot/reconnection.
- Name resolution converts numeric IP addresses into human-readable hostnames (and vice versa) — e.g., resolving a domain to its IP.
hostname(no arguments) shows the current system's hostname.localhost(address127.0.0.1) always refers to the current machine itself.
Key configuration files:
/etc/resolv.conf— lists DNS name servers the system queries (older systems list them directly; modernsystemd-resolved-based systems use a local caching DNS stub resolver)./etc/hosts— a static, local hostname-to-IP mapping file, checked before DNS is consulted. Useful for local-network shortcuts (multiple names can map to the same IP).
DNS Lookup Tools:
host somesite.com # basic DNS lookup
nslookup somesite.com # similar; slightly different, more compact output format
dig somesite.com # most detailed — shows the full resolution/query process
ping hostname # tests reachability; also resolves the hostname via /etc/hosts or DNS| Family | Legacy Config Location |
|---|---|
| Debian | /etc/network/ |
| Red Hat / SUSE | /etc/sysconfig/network |
Modern systems rely on NetworkManager, reducing the need to directly edit these files. Command-line NetworkManager tools:
nmtui # text-based UI for NetworkManager — nearly identical appearance across distributions
nmcli # command-line interface — even more consistent/minimal across distrosip addr show # (modern) view all interfaces and their IP addresses
ip route show # (modern) view the routing table
ifconfig # (older/legacy) view interface info — may need to be installed on newer distros (net-tools package)
route # (older/legacy) view/manage routing table
ipis newer, more powerful, but has less human-friendly output formatting than the olderifconfig/routetools.
ping hostname_or_ip # sends continuous packets; press Ctrl+C to stop
ping -c 4 hostname_or_ip # -c limits the number of packets sent (recommended, to avoid excessive network load)Confirms whether a remote host is online and responding — a summary of packet loss/timing is shown when it stops.
route # (legacy) view/manage the routing table
ip route show # (modern) view the routing table
ip route add ... # add a static routeRouters use these tables to determine the next hop toward a packet's final destination, potentially crossing multiple networks.
Shows the actual path (sequence of hops/routers) a packet takes to reach a destination — useful for diagnosing network delays/errors by isolating which hop is causing issues.
traceroute hostname_or_ipsudo ethtool eth0 # query/configure a network interface's low-level settings
netstat -r # display active connections and routing tables (older tool; `ss` is the modern replacement)
sudo nmap -sP 10.0.2.0/24 # scan a network range for open hosts/ports- Graphical: Firefox, Google Chrome, Chromium, Konqueror, Opera
- Text-based (non-graphical): links, links2, w3m
wget — command-line downloader; supports large files, recursive downloads (following links across pages), password-protected downloads, and multi-file downloads:
wget https://example.com/file.zip # download a single filecurl — retrieve/inspect URL content (headers, source), or save it to a file; works well in scripts:
curl http://example.com # print page content to terminal
curl -s -o saved.html http://example.com # save output to a file (-o), silent mode (-s)SSH (Secure Shell) — cryptographic protocol for secure remote login and command execution:
ssh someuser@remotehost # log in with a specific username
ssh remotehost # log in with your CURRENT local username
ssh remotehost "some-command" # run a single remote command via SSH without opening an interactive session- First-time connections prompt you to confirm the remote host's authenticity (fingerprint verification).
- Can be configured for passwordless access using key-based authentication.
SCP (Secure Copy) — securely copies files/directories between networked hosts, using the SSH protocol:
scp localfile.txt user@remotehost:/home/user/ # copy a LOCAL file TO a remote system
scp -r somedirectory user@remotehost:/tmp/ # -r for recursive directory copies
scp user@remotehost:/path/to/remotefile.txt . # copy FROM a remote system TO local- An IP address is a unique logical network address assigned to a device.
- IPv4 uses 32-bit addresses; IPv6 uses 128-bit addresses.
- Every IP address contains a network portion and a host portion.
- There are 5 network address classes: A, B, C, D, and E.
- DNS converts domain/host names into IP addresses.
ifconfig(legacy) orip addr show/ip route show(modern) display interface and routing information.pingtests remote host reachability;route/ip routemanage routing;traceroutediagnoses path/hop issues.- Firefox, Chrome, Chromium, and Epiphany are common graphical browsers;
links/links2/w3mare text-based alternatives. wgetdownloads files/pages;curlretrieves/inspects URL data.sshruns remote commands/sessions securely;scpsecurely copies files between networked hosts.
| Category | Command | Purpose |
|---|---|---|
| Navigation | pwd, cd, ls, tree |
Move around and list the file system |
| Files | touch, cp, mv, rm, mkdir, rmdir |
Create/copy/move/delete files & directories |
| Links | ln, ln -s |
Hard and symbolic links |
| Viewing | cat, tac, less, head, tail, more |
View file contents |
| Searching | locate, find, grep, which, whereis |
Find files, programs, and text patterns |
| Text processing | sed, awk, sort, uniq, cut, tr, wc, paste, join, split, tee |
Manipulate and transform text data |
| Comparing | diff, diff3, cmp, patch |
Compare files and apply changes |
| Permissions | chmod, chown, chgrp |
Manage file access rights and ownership |
| Users/Groups | useradd, userdel, usermod, groupadd, groupdel, groupmod, id, who, whoami |
Manage accounts |
| Privilege | su, sudo |
Elevate privileges |
| Processes | ps, top, pstree, kill, renice, jobs, bg, fg |
Manage running processes |
| Scheduling | at, cron/crontab, sleep |
Schedule tasks |
| Package mgmt (Debian) | dpkg, apt, apt-get, apt-cache |
Install/remove software |
| Package mgmt (Red Hat) | rpm, dnf, yum |
Install/remove software |
| Package mgmt (SUSE) | rpm, zypper |
Install/remove software |
| Disk/File systems | mount, umount, df, du |
Manage mounted file systems and disk usage |
| Backup/Sync | cp, rsync |
Copy and synchronize data |
| Compression | gzip, bzip2, xz, zip/unzip, tar |
Compress/archive files |
| Networking | ip, ifconfig, ping, route, traceroute, ssh, scp, wget, curl, host, nslookup, dig |
Network diagnostics and remote access |
| Documentation | man, info, --help, help, apropos, whatis |
Get help |
| Text editors | nano, gedit, vi/vim, emacs |
Edit files |
| Shell/Environment | alias, export, env, history, echo |
Customize the shell environment |
- Three major distribution families exist: Red Hat (RPM, yum/dnf), SUSE (RPM, zypper), and Debian (dpkg, apt) — each with its own philosophy, but all ultimately provide similar core Linux capabilities.
- Everything is treated as a file in Linux — from documents to devices — enabling a consistent I/O model across very different resource types.
- The boot process flows: BIOS/UEFI → Boot Loader (GRUB) → Kernel → initramfs → init/systemd → login.
- The file system hierarchy is standardized (FHS) — key directories include
/etc(config),/var(variable data/logs),/home(user data),/proc(live kernel/process info),/boot(kernel files), and/bin//usr/bin(executables). - GNOME is the most common desktop environment across all three families, though its look-and-feel varies by distribution.
- The command line is the most powerful, most portable interface — nearly identical across all distributions, and essential for automation, remote administration, and complex tasks.
sudois preferred oversufor elevated privileges — safer, more auditable, and limits scope.- Absolute paths start with
/; relative paths don't — understanding this distinction is fundamental to efficient navigation. findsearches live;locatesearches a cached database — know when to use each.- Process management revolves around PIDs, nice values (-20 highest priority to +19 lowest), and tools like
ps(snapshot) vs.top(live monitoring). - Text processing tools (
grep,sed,awk,sort,cut, etc.) are the backbone of efficient Linux administration and scripting — mastering pipes (|) and redirection (>,>>,<) multiplies their power. - Vi/Vim is universally available — even if you prefer another editor, basic Vi proficiency is a safety net for any Linux/Unix system you encounter.
- File permissions follow the read/write/execute model across owner/group/others, controlled via
chmod(symbolic or octal) and ownership viachown/chgrp. - Networking fundamentals — IPv4 (32-bit) vs. IPv6 (128-bit) addressing, DNS resolution, and essential tools (
ping,ssh,scp,wget,curl) — round out the practical skill set needed to administer Linux systems both locally and remotely.
End of course notes. For further study, the companion text-based version of this course also includes additional sections on Bash shell scripting, printing, and local security principles.