Linux: Command Line Essentials
Master core filesystem navigation, file operations, content inspection, manual pages, and terminal productivity shortcuts on Ubuntu 24.04 LTS.
2.1 Navigating the Filesystem
Linux organizes all files, directories, physical storage devices, and virtual process files into a single unified hierarchical tree starting at the root directory (/). Navigating this structure efficiently forms the baseline skill of every system administrator.
2.1.1 Core Navigation Commands: pwd, ls, cd
Three fundamental utilities handle location discovery, directory listing, and directory traversal:
| Command | Common Flags | Functional Purpose | Example Usage |
|---|---|---|---|
| pwd | -P (physical) | Print working directory (displays your exact location in the tree) | pwd |
| ls | -l, -a, -h, -t, -F | List directory contents, file permissions, owners, and sizes | ls -lah /var/log |
| cd | -, ~, .., . | Change current directory to a target relative or absolute path | cd /etc/nginx |
Useful ls Flag Combinations
- ls -l:Long listing format showing permissions, hard link count, owner, group, file size, and timestamp.
- ls -a:Show all files, including hidden dotfiles that start with a period.
- ls -lh:Human-readable file sizes displaying values in K, M, or G instead of raw bytes.
- ls -lt:Sort files by modification time with newest files displayed first.
- ls -R:Recursively list all subdirectories and their contents.
2.1.2 Absolute vs Relative Paths
Every file target is specified using one of two path styles:
Path Resolution Rules
- Absolute Paths:Always start with the root slash (
/). They define an unambiguous route from the base of the filesystem regardless of where your current shell is located (e.g.,/etc/systemd/systemor/var/www/html). - Relative Paths:Do not begin with a leading slash. They calculate the target relative to your current working directory (e.g., typing
cd logsinside/varnavigates to/var/logs).
2.1.3 The Home Directory, ~, ., and ..
Special directory symbols provide quick shortcuts across the shell:
Special Path Notations
- Tilde (~):Expands to the current user home directory (e.g.,
/home/studentor/root). Typingcd ~or simplycdreturns you home instantly. - Single Dot (.):Represents the current working directory. Useful when running local executable scripts (e.g.,
./deploy.sh) or specifying copy destinations (e.g.,cp /tmp/file.txt .). - Double Dot (..):Represents the parent directory one level above. Moving up two levels is written as
cd ../... - Minus Symbol (cd -):Switches back to your previous working directory, identical to an undo button for directory navigation.
2.1.4 Tab Completion and Command History
Typing commands manually is slow and error-prone. Bash provides built-in acceleration mechanisms:
Shell Acceleration Features
- Tab Completion:Pressing
Tabonce auto-completes unique command names, file paths, and options. PressingTabtwice lists all matching candidates. - Command History:The
historycommand prints previous shell instructions numbered chronologically. Rerun command 42 by typing!42. - Double Exclamation (!!):Repeats the immediate last command. Useful when forgetting root permissions: type
sudo !!to execute the previous command with elevated rights.
2.2 Working with Files and Directories
Creating, organizing, copying, moving, and removing items are everyday terminal operations. Mastering their safe syntax prevents unintended data loss.
2.2.1 touch, mkdir, cp, mv
Creation and Management Commands
- touch filename:Creates a new zero-byte empty file if it does not exist, or updates access and modification timestamps if it already exists.
- mkdir dirname:Creates a new directory. Use the parent flag
mkdir -p project/src/componentsto generate nested folder hierarchies in a single execution without errors. - cp source destination:Copies files. To copy directories with all child contents, the recursive flag is required:
cp -r source_dir/ target_dir/. Usecp -ito prompt before overwriting. - mv source destination:Moves or renames files and directories. Moving an item within the same filesystem simply updates filesystem metadata rather than transferring disk blocks.
2.2.2 rm and rmdir (and Why Caution is Mandatory)
Linux does not provide a desktop recycle bin by default. When an unprivileged or root process removes an unlinked file, the storage blocks are marked available immediately:
Deletion Safety Rules
- rmdir dirname:Removes only completely empty directories. Fails safely if files or subdirectories remain inside.
- rm -r dirname:Recursively deletes a directory along with all nested contents.
- rm -i filename:Interactive deletion mode that asks for confirmation before removing each target.
- The rm -rf danger:The
-f(force) flag suppresses all confirmation warnings and missing file notifications. Runningsudo rm -rf /or malformed path variables likerm -rf $DIR/*where$DIRis unset wipes the root filesystem.
2.2.3 Wildcards and Globbing
Shell globbing allows matching groups of filenames using pattern characters expanded by the shell before the command executes:
Globbing Pattern Operators
- Asterisk (*):Matches zero or more characters. For example,
ls *.loglists every file ending in .log. - Question Mark (?):Matches exactly one single character. For example,
file?.txtmatches file1.txt and fileA.txt, but not file10.txt. - Character Set ([abc]):Matches any single character enclosed in brackets. For example,
data[0-9].csvmatches data0.csv through data9.csv. - Negation ([!abc]):Matches any character not enclosed within the brackets.
- Brace Expansion ({a,b,c}):Generates arbitrary string permutations directly. For example,
touch server_{prod,staging,dev}.confcreates three separate configuration files in one command.
2.2.4 Hidden Files (Dotfiles)
Any file or folder whose name starts with a period (.) is treated as a hidden file by Linux file tools. User environment configs (like .bashrc, .profile, and .ssh) use this convention to keep standard directory listings uncluttered. Run ls -a to inspect them.
2.3 Viewing File Contents
Opening large files in an interactive text editor just to read configuration lines or inspect log outputs consumes unnecessary memory and risks accidental edits. Specialized command line viewers solve this efficiently.
2.3.1 cat, less, head, tail
File Viewing Tools
- cat filename:Concatenates and prints the entire file to standard output. Use
cat -nto display line numbers. Best suited for short files under 50 lines. - less filename:A terminal pager that opens files without loading the full content into RAM. Navigate with
Space(page forward),b(page backward),/pattern(search forward),g(top of file),G(end of file), andq(quit). - head -n [count] filename:Displays the first N lines of a file (defaults to 10 lines if unspecified). Example:
head -n 25 /etc/passwd. - tail -n [count] filename:Displays the last N lines of a file (defaults to 10 lines). Example:
tail -n 50 /var/log/syslog.
2.3.2 Streaming Live Logs with tail -f
When diagnosing active server services or watching incoming HTTP requests, standard static outputs are insufficient. The follow flag streams appended lines in real time:
Live Log Inspection
- tail -f /var/log/nginx/access.log:Keeps the file descriptor open and streams newly written lines directly to your terminal screen as clients connect.
- tail -F (Follow by Name):Monitors the file by filename rather than descriptor. If the system logrotate daemon archives and recreates the log,
tail -Fautomatically reopens the new file without dropping the stream. - Stopping the Stream:Press
Ctrl+Cat any time to send the interrupt signal and return to the shell prompt.
2.3.3 File Metrics and Metadata: wc, file, stat
Inspection Utilities
- wc filename (Word Count):Prints line, word, and byte counts. Use
wc -lfor line counts,wc -wfor words, andwc -cfor raw byte size. - file filename:Inspects magic numbers in the file header to determine the genuine file format regardless of any misleading file extension (e.g., detecting an ELF binary named picture.png).
- stat filename:Reports detailed filesystem metadata: exact byte size, block allocation count, inode number, permission bits, and timestamps for Access, Modify, and Change.
2.4 Getting Help Directly in the Terminal
Linux systems include thorough documentation directly within the installation. System administrators do not memorize every single flag; they know how to consult the internal manual systems.
2.4.1 Manual Pages (man)
The man command opens formatted documentation organized into numbered sections:
Manual Page Sections
- Section 1:User commands and executable programs (e.g.,
man 1 ls). - Section 5:File formats and configuration file conventions (e.g.,
man 5 crontaborman 5 passwd). - Section 8:System administration commands used primarily by root (e.g.,
man 8 useradd). - Keyword Search (man -k):Searches short descriptions for matching topics (e.g.,
man -k partition). Same as runningapropos partition.
2.4.2 Fast Reference: --help, info, tldr
Quick Documentation Options
- command --help:Prints a concise summary of flags and syntax options straight to standard output without opening a fullscreen pager.
- info command:GNU project documentation presenting hypertext menu trees with deeper explanations than traditional man pages.
- tldr command:A popular community tool that provides practical, real-world command line examples instead of exhaustive specification sheets.
2.4.3 Identifying Commands: which, whereis, type, alias
Command Identification Utilities
- which binary:Locates the executable binary in the directories listed in your current
$PATH(e.g.,which python3returns/usr/bin/python3). - whereis binary:Locates binary files, manual page documentation files, and source code files simultaneously.
- type -a command:Reveals how the shell interprets a name (whether it is an internal shell builtin, a function, an alias, or an external disk binary).
- alias name='command':Creates a shortcut for frequently used commands with preset flags (e.g.,
alias ll='ls -lah'). Stored in~/.bashrcfor persistence.
2.5 Command Line Productivity
Fluid keyboard interaction, environment variable awareness, logical execution chaining, and proper shell quoting distinguish novice users from productive engineers.
2.5.1 Essential Keyboard Shortcuts
| Shortcut | Action Performed | Common Scenario |
|---|---|---|
| Ctrl + C | Sends SIGINT interrupt signal | Cancels a hung process or clears the active command line |
| Ctrl + L | Clears the terminal display | Refreshes screen real estate without losing scrollback history |
| Ctrl + R | Reverse incremental history search | Finds complex previously typed commands by typing a keyword |
| Ctrl + A | Jumps cursor to the line start | Quickly prepends sudo to a long command |
| Ctrl + E | Jumps cursor to the line end | Appends flags or arguments to an existing instruction |
| Ctrl + U | Cuts text from cursor backward to line start | Wipes out a mistyped argument or password field |
| Ctrl + K | Cuts text from cursor forward to line end | Removes tail parameters while preserving base command |
2.5.2 Environment Variables and the PATH Variable
Environment variables store settings and system states shared across processes:
Environment Management
- Inspecting Variables:Use
printenvorenvto view all active variables, orecho $VARIABLE_NAMEfor specific ones (e.g.,echo $USER,echo $HOME,echo $SHELL). - The $PATH Variable:A colon-separated list of directories searched in order whenever you run a command without an absolute path (e.g.,
/usr/local/bin:/usr/bin:/bin). - Exporting Variables:Setting a variable like
APP_ENV=productionrestricts it to the current shell. Usingexport APP_ENV=productionpasses it to all child processes and scripts spawned from this terminal.
2.5.3 Chaining Commands: ;, &&, ||
Every Linux process finishes with an exit status code (accessible via echo $?). A status of 0 indicates success, while any non-zero value indicates an error. Operators evaluate this exit code:
| Operator | Name | Execution Condition | Practical Example |
|---|---|---|---|
| ; | Semicolon | Runs sequentially regardless of whether the previous command succeeded or failed | date; whoami; uptime |
| && | Logical AND | Runs the second command only if the first command exits with status 0 (success) | mkdir build && cd build |
| || | Logical OR | Runs the second command only if the first command exits with a non-zero status (failure) | ping -c 1 host || echo "Server down" |
2.5.4 Quoting and Escaping
When working with file names containing whitespace, special characters, or variables, quotes dictate shell expansion:
Quoting Mechanisms
- Single Quotes (' '):Preserves the literal value of every character enclosed. No variable expansion, no globbing, and no command substitution occurs (e.g.,
echo '$USER'prints$USER). - Double Quotes (" "):Preserves literal text for most characters but permits variable expansion (
$VAR), command substitution ($(date)), and arithmetic ($((1+1))). - Backslash Escape (\):Strips special meaning from the immediate next character. Use to handle literal spaces in filenames:
cat My\ File.txtor literal quotes:echo \"hello\".
Knowledge Check: Module 2 Command Line Essentials
1. What does the command "cd -" do in Bash?
2. Which option makes the rm command ask before deleting files?
3. Which command streams incoming log entries in real time?
4. What happens when commands are joined with "&&"?
5. Which keyboard shortcut moves the cursor to the start of the line?
6. How do single quotes treat shell variables in Bash?