Chapter 1
System Management
Course: Comptia Linux Xk0 006
Subject: Comptia Linux Xk0 006
Chapter: System Management
Linux provides a powerful set of utilities for editing, formatting, parsing, and transforming files—particularly useful for text-based configurations, scripts, and logs. Below are essential tools used in both day-to-day admin tasks and scripting automation.
1. File Editing Tools in Linux
Linux provides powerful command-line tools for editing and processing files—especially text files. These tools are widely used in scripting, automation, log parsing, and report generation.
1. sed – Stream Editor
sed is a non-interactive, stream-oriented text editor designed for parsing and transforming text from files or standard input. It's ideal for batch operations and scripting where edits need to be automated.
Syntax:
bash
sed 's/pattern/replacement/' file
Common Examples:
- Replace the first occurrence of "apple" with "orange" per line: bash sed 's/apple/orange/' file.txt
- Replace all occurrences of "apple" in each line: bash sed 's/apple/orange/g' file.txt
- Edit in place and keep a backup of the original: bash sed -i.bak 's/foo/bar/g' config.conf
- Delete blank lines: bash sed '/^$/d' file.txt
Real-life use case:
Automating a version update in configuration files:
bash
sed -i 's/version=1.0/version=2.0/' app.cfg
This is useful during CI/CD deployments or version upgrades across multiple configuration files.
2. awk – Pattern Scanning and Processing Language
awk is a text-processing language that works well for structured, line-based data such as logs, reports, or CSV files. It reads files line by line, splits them into fields, and performs operations based on patterns or conditions.
Syntax:
bash
awk 'pattern { action }' file
Common Examples:
- Print the second column from a space-separated file: bash awk '{print $2}' data.txt
- Print lines where the third column is greater than 100: bash awk '$3 > 100' sales.csv
- Calculate the sum of the first column: bash awk '{sum += $1} END {print sum}' numbers.txt
- Print specific fields with formatting: bash awk '{printf "%-10s %-5s\n", 2}' users.txt
Real-life use case:
Generate a report of how many times each IP appears in a web server log:
bash
awk '{ip[$1]++} END {for (i in ip) print i, ip[i]}' access.log
This is often used in security analysis and traffic auditing.
3. printf – Formatted Output
printf is used to print formatted strings and numbers to standard output. Unlike echo, it gives fine-grained control over alignment, padding, decimal precision, and string formatting—making it essential in scripts and reporting.
Syntax:
bash
printf "format string" values
Common Examples:
- Print left-aligned columns with fixed width: bash printf "%-10s %-10s\n" "User" "Score"
- Format floating-point numbers to 2 decimal places: bash printf "Total: $%.2f\n" 123.456
- Combine strings and variables in scripts: bash name="Alice" score=92 printf "Student: %s, Score: %d%%\n" "score"
Real-life use case:
Format a neat header and output for a disk usage report:
bash
printf "%-20s %-10s\n" "Filename" "Size (MB)"
4. nano – Simple Command-Line Text Editor
nano is a beginner-friendly, non-modal terminal text editor. It is ideal for quick edits, especially when ease-of-use is more important than advanced features.
Usage:
bash
nano filename.txt
Common Shortcuts:
- Ctrl + O → Write (save) changes to disk
- Ctrl + X → Exit the editor
- Ctrl + W → Search for a keyword
- Ctrl + K → Cut the current line
- Ctrl + U → Paste the last cut line
Use the ^ symbol as shorthand for Ctrl. For example, ^O = Ctrl + O.
Features:
- Displays command hints at the bottom of the screen
- Supports syntax highlighting (limited)
- Good for small scripts, notes, crontab edits
Real-life use case:
Editing the system's crontab file to schedule backups:
bash
nano /etc/crontab
This allows a system admin to add or adjust scheduled tasks quickly without dealing with modal editors.
5. vi / vim – Advanced Command-Line Editor
vi is the standard Unix text editor, and vim (Vi IMproved) is its more powerful, feature-rich successor. It is modal, meaning its behavior changes based on the current mode (command, insert, etc.).
Modes in vim:
- Normal mode (default): Navigate and issue commands
- Insert mode: Type text (i, a, o to enter)
- Command mode: Used to save, quit, search (: prefix)
Usage:
bash
vim filename.txt
Essential Commands:
| Mode | Key | Description | | Normal | i | Enter insert mode | | Normal | dd | Delete current line | | Normal | /text | Search for “text” | | Command | :w | Save file | | Command | :q | Quit | | Command | :wq | Save and quit | | Command | :q! | Force quit without saving |
Features:
- Syntax highlighting for programming/configuration files
- Support for macros, scripting, buffers, and plugins
- Efficient navigation and manipulation with keyboard only
- Lightweight and fast even on remote servers
Real-life use case:
A system administrator SSHs into a server and modifies /etc/hosts to add a new hostname:
bash
vim /etc/hosts
vim is preferred here because of its performance, advanced capabilities, and availability on nearly all Unix/Linux systems.
Summary Table
| Tool | Purpose | Interactive? | Strengths | Real-life Use Case | | sed | Stream editing | No | Fast, scriptable replacements | Auto-replace values in config files | | awk | Data processing and filtering | No | Great for logs and columnar data | Summing column data from a CSV | | printf | Formatted output | No | Precision formatting for reports or logs | Formatting CLI output in a script | | nano | Simple file editing | Yes | Easy to use, ideal for quick edits | Modify crontab or text notes | | vim | Advanced text editing | Yes | Highly efficient for large file editing | Editing /etc/fstab or writing scripts |
2. File Compression, Archiving, and Backup in Linux
In Linux systems, file compression and archiving are essential tasks for reducing disk usage, simplifying file transfer, and creating backups. Compression algorithms reduce file size, while archiving combines multiple files into a single package. Tools like gzip, bzip2, and zip are commonly used for these purposes.
1. gzip – GNU Zip Compression
gzip is one of the most commonly used compression utilities in Unix-like systems. It compresses files using the DEFLATE algorithm, which provides a good balance between speed and compression ratio.
Key Characteristics:
- Compresses a single file (creates .gz)
- Original file is removed unless -k (keep) is specified
- Typically used with tar to compress entire directories (.tar.gz)
- Fast compression, moderate file size reduction
Usage:
bash
gzip filename.txt
This creates filename.txt.gz and deletes the original file.
Common Options:
- -k: Keep original file
- -d: Decompress (or use gunzip)
- -r: Recursively compress files in directories
Example – compress a file:
bash
gzip -k report.log
Example – decompress:
bash
gunzip report.log.gz
Real-life use case:
Compressing large log files before archiving them to save disk space:
bash
gzip /var/log/syslog
2. bzip2 – Burrows-Wheeler Compression
bzip2 offers higher compression ratios than gzip, but it is slower in both compression and decompression. It uses the Burrows-Wheeler algorithm, which is more efficient at compressing repetitive data.
Key Characteristics:
- Produces .bz2 files
- Slower but better compression than gzip
- Often used with tar (.tar.bz2)
- Original file is removed by default
Usage:
bash
bzip2 filename.txt
Decompress:
bash
bunzip2 filename.txt.bz2
Example – keep the original:
bash
bzip2 -k filename.txt
Real-life use case:
Compressing large source code archives or database exports to reduce transmission time:
bash
tar cf source.tar source_code/ bzip2 source.tar # Result: source.tar.bz2
3. zip – Archive + Compression in One
zip is a widely-used format on Windows, Linux, and macOS that compresses and archives files in one step. Unlike gzip or bzip2, zip can compress multiple files and directories in one go.
Key Characteristics:
- Combines and compresses multiple files into one .zip file
- Keeps original files by default
- Supports password protection and encryption
- Compatible across platforms
Usage:
bash
zip archive.zip file1.txt file2.txt
Common Options:
- -r: Recursively zip directories
- -e: Encrypt archive with a password
- -q: Quiet mode
Unzip:
bash
unzip archive.zip
Example – compress a folder recursively:
bash
zip -r project_backup.zip /home/user/project/
Real-life use case:
Creating portable archives for sharing code or documents with Windows users:
bash
zip -r project.zip project_folder/
4. tar – Tape Archive
tar is not a compression tool by itself but an archiving utility that collects multiple files/directories into a single file called a "tarball." Compression is typically added using gzip, bzip2, or xz.
Key Characteristics:
- Combines multiple files into one .tar archive
- Supports appending, listing, and extracting files
- Often used with gzip (.tar.gz) or bzip2 (.tar.bz2)
Common Syntax:
bash
tar [options] archive_name.tar files
Common Options:
- -c: Create archive
- -x: Extract archive
- -v: Verbose (list files being processed)
- -f: Specify archive file
- -z: Use gzip
- -j: Use bzip2
- -J: Use xz
Example – create a compressed archive:
bash
tar -czvf backup.tar.gz /home/user/project
Example – extract:
bash
tar -xvzf backup.tar.gz
Real-life use case:
Archiving a project directory before deployment or backup.
5. xz – High-Ratio Compression Tool
xz is a compression utility that uses the LZMA2 algorithm. It provides better compression ratios than gzip and bzip2, but is slower—ideal when maximum compression is more important than speed.
Key Characteristics:
- Produces .xz files
- High compression, slower than gzip
- Often used with tar (.tar.xz)
Usage:
bash
xz file.txt
Decompress:
bash
unxz file.txt.xz
Example – combine with tar:
bash
tar -cJf archive.tar.xz myfolder/
Real-life use case:
Compressing large software source packages for distribution where disk space or download size matters.
6. cpio – Copy In and Out Archiving Tool
cpio is an older but still-used archiving tool that works well for piping file lists into an archive. It's used in system-level packaging and initramfs creation.
Key Characteristics:
- Reads list of files from stdin
- Works well with find, making it scriptable
- Common in Linux kernel and initrd/initramfs generation
Create an archive:
bash
find . -type f | cpio -ov > backup.cpio
Extract:
bash
cpio -idv < backup.cpio
Real-life use case:
Used internally by the Linux boot process to create compressed initramfs images, and also for legacy UNIX backup scripts.
7. dd – Disk Dump Utility
dd is a low-level utility used to copy and convert raw data. It is commonly used for disk cloning, creating bootable media, or making disk images.
Key Characteristics:
- Operates at the byte/block level
- Can copy entire drives or partitions
- Used for disk imaging and forensic backups
Syntax:
bash
dd if=input_file of=output_file [options]
Common Options:
- if=: Input file or device (e.g., /dev/sda)
- of=: Output file or device
- bs=: Block size (e.g., bs=4M)
- status=progress: Show progress during operation
Example – create a disk image:
bash
dd if=/dev/sda of=/mnt/backup/disk.img bs=4M status=progress
Example – create a bootable USB:
bash
dd if=linux.iso of=/dev/sdX bs=4M status=progress && sync
Real-life use case:
System administrator creates a raw backup of an entire disk before wiping it, or prepares a bootable ISO image for OS installation.
3. File Metadata in Linux
In Linux, file metadata refers to information about a file, rather than its actual content. This includes properties like permissions, ownership, timestamps, size, file type, and more. Inspecting metadata helps users and administrators troubleshoot file-related issues, manage access control, and understand system behavior.
Two commonly used tools to examine file metadata are stat and file.
1. stat – Display Detailed File Information
The stat command provides detailed metadata about a file, including access/modification times, size, block usage, and permission details.
Syntax:
bash
stat filename
Example Output:
bash
File: myscript.sh Size: 2048 Blocks: 8 IO Block: 4096 regular file Device: 802h/2050d Inode: 654321 Links: 1 Access: 2025-04-01 10:23:15.000000000 +0000 Modify: 2025-04-01 09:45:00.000000000 +0000 Change: 2025-04-01 09:45:10.000000000 +0000 Birth: -
Key Fields Explained:
- Size: File size in bytes
- Blocks: Number of 512-byte blocks used
- Access: Last time the file was read
- Modify: Last time file content was changed
- Change: Last time file metadata changed
- Inode: Unique file identifier on the filesystem
Real-life use case:
A sysadmin uses stat to confirm when a configuration file was last modified:
bash
stat /etc/nginx/nginx.conf
This helps troubleshoot if a service issue is caused by recent changes.
2. file – Determine File Type Based on Content
The file command identifies a file’s type and encoding based on its content, not its extension. It uses magic numbers and pattern matching to infer what kind of data a file holds.
Syntax:
bash
file filename
Example Outputs:
bash
file image.png
image.png: PNG image data, 800 x 600, 8-bit/color RGB
file script.sh
script.sh: Bourne-Again shell script, ASCII text executable
file unknown_file
unknown_file: gzip compressed data, was "archive.tar", last modified...
Real-life use case:
A developer downloads a file with no extension and wants to know its type:
bash
file downloaded_file
This quickly reveals if the file is a ZIP, shell script, binary, or image—preventing accidental execution of unsafe content.
Comparison: stat vs file
| Command | Purpose | Returns | Useful For | | stat | Shows file metadata | Timestamps, size, permissions, etc. | Auditing file changes, ownership, access issues | | file | Determines file type (content) | MIME type, encoding, format | Identifying unknown or mislabeled files |
4. Soft and Hard Links in Linux
Linux filesystems (like ext4, XFS, Btrfs) support two types of links that reference files: hard links and soft links (also called symbolic links or symlinks). Both allow multiple filenames to refer to the same data on disk but differ in how they are implemented and behave.
1. Hard Links
A hard link is a direct reference to a file’s inode—the low-level data structure that stores file metadata and disk block pointers.
Key Characteristics:
- Points to the same inode as the original file.
- Both the original and hard link are equal—no "parent" or "child".
- Deleting the original file does not remove the data as long as at least one hard link exists.
- Cannot link to directories (for safety).
- Must reside on the same filesystem as the target file.
Syntax:
bash
ln original.txt hardlink.txt
Example:
bash
echo "hello world" > file.txt ln file.txt file_hardlink.txt
Now both file.txt and file_hardlink.txt point to the same inode. Changes to one affect the other.
View hard link count:
bash
ls -l
Look for the second column – the link count
Real-life use case:
Used in backup systems or version control mechanisms where files should share the same data without duplication until explicitly changed (like in rsync --link-dest).
2. Soft Links (Symbolic Links)
A symbolic link is a special file that contains a path to another file or directory. It acts like a shortcut or alias.
Key Characteristics:
- Points to the pathname, not the inode.
- Can link to files or directories.
- If the target file is deleted or moved, the symlink becomes broken (dangling).
- Can span across filesystems.
Syntax:
bash
ln -s target.txt symlink.txt
Example:
bash
ln -s /var/log/syslog mylog
mylog will point to /var/log/syslog, and reading or editing it is the same as acting on the original file.
Identify symlinks:
bash
ls -l
You’ll see something like: mylog -> /var/log/syslog
Real-life use case:
Used in /etc to link configuration files, or in /usr/bin to point commands to the right binaries:
bash
ls -l /usr/bin/python
python -> /usr/bin/python3.8
Comparison Table
| Feature | Hard Link | Soft Link (Symlink) | | Points to | File’s inode | File's name/path | | Survives file deletion | Yes | No (becomes broken) | | Can link to directories | No | Yes | | Cross-filesystem link | No | Yes | | Use case | Redundant backup, deduplication | Shortcuts, path redirection | | Command syntax | ln original link | ln -s target link |
Detecting and Inspecting Links
- Check file type: bash file filename
- List inode numbers and link counts: bash ls -li
- Follow symlink to the real file: bash readlink -f symlink
5. Copying Files Between Systems in Linux
Transferring files across systems is a common administrative task in Linux environments. Whether you're syncing backups, copying configuration files, or migrating data across servers, Linux offers several tools for secure, fast, and flexible file transfer.
1. rsync – Remote File Synchronization
rsync is a powerful and flexible tool used to efficiently synchronize files and directories between two systems over SSH or locally. It only transfers differences (deltas) between source and destination files, making it highly efficient for incremental backups.
Key Characteristics:
- Supports compression, partial transfers, and resuming
- Preserves permissions, timestamps, symlinks, ownership
- Works over SSH by default
- Can delete files on the destination that are no longer present in the source (--delete)
- Ideal for backups, mirroring, and one-way syncs
Basic Syntax:
bash
rsync [options] source destination
Examples:
- Copy a local directory to a remote server: bash rsync -avz /home/user/data/ user@remote:/backup/data/
- Sync remote directory to local, deleting extraneous files: bash rsync -avz --delete user@remote:/var/www/ ./mirror_www/
Real-life use case:
A sysadmin schedules rsync with cron to back up /etc and /var/www from a web server to a remote NAS each night:
bash
rsync -az /etc /var/www user@backup-server:/nightly/
2. scp – Secure Copy
scp (secure copy) is a simpler alternative to rsync for copying files over SSH. It’s part of the OpenSSH suite and works similarly to cp, but supports remote paths.
Key Characteristics:
- Copies entire files (no delta sync)
- Uses SSH for encryption and authentication
- Doesn’t preserve metadata by default (unless -p is used)
- Easy to use for one-off transfers
Syntax:
bash
scp [options] source destination
Examples:
- Copy a file to a remote system: bash scp backup.sql [email protected]:/home/user/
- Copy from a remote server to local: bash scp [email protected]:/var/log/syslog ./logs/
- Recursive copy (directories): bash scp -r mydir user@host:/path/
Real-life use case:
A developer quickly transfers a database dump from their laptop to a staging server before testing:
bash
scp db.sql user@staging:/tmp/
3. nc (Netcat) – Raw TCP Transfer Tool
nc (netcat) is a low-level networking tool that can be used to send files over TCP/UDP sockets. It's extremely flexible but lacks built-in encryption or authentication.
Key Characteristics:
- Very fast for large file transfers in trusted networks
- No encryption (use only on secure networks or wrap with SSH tunnels)
- Not meant for long-term use but great for quick ad-hoc transfers
- Useful for piping raw data (e.g., disk images, logs)
Syntax:
On the receiving machine (listening):
bash
nc -l -p 1234 > received_file
On the sending machine:
bash
nc remote_host 1234 < file_to_send
Real-life use case:
An admin needs to transfer a large ISO between two systems on a local network without overhead:
bash
Receiver:
nc -l -p 5555 > ubuntu.iso
Sender:
nc 192.168.1.10 5555 < ubuntu.iso
Comparison Table
| Tool | Encryption | Delta Transfer | Speed | Ease of Use | Use Case | | rsync | Yes (via SSH) | Yes | Moderate | Moderate | Efficient backups, syncs, mirroring | | scp | Yes | No | Fast | Easy | One-time secure transfers | | nc | No | No | Very fast | Requires setup | Local fast copies, bulk raw file transfers |
Security Notes:
- Always prefer rsync or scp over nc on public or untrusted networks due to encryption.
- If using nc, you can encrypt with SSH manually (e.g., tunneling) or use openssl as an alternative with TLS.
6. File and Directory Operations
Linux file systems are manipulated primarily using command-line tools.
1. mv – Move or Rename Files and Directories
The mv command is used to move files and directories from one location to another or to rename them. It does not duplicate the file; it simply changes its location or name.
Syntax:
bash
mv [options] source destination
Key Characteristics:
- Overwrites the destination file if it exists (unless -i is used)
- Supports renaming by moving within the same directory with a new name
- Faster than cp for large files since no data is duplicated
Common Options:
- -i: Prompt before overwriting
- -f: Force overwrite without prompting
- -n: Do not overwrite existing files
Examples:
- Rename a file: bash mv report.txt final_report.txt
- Move a file to another directory: bash mv backup.sql /var/backups/
- Move all .log files into a directory: bash mv *.log logs/
Real-life use case:
After generating daily reports, a script moves them into an archive directory:
bash
mv /reports/*.csv /reports/archive/
2. cp – Copy Files and Directories
The cp command is used to copy files or directories, creating an exact duplicate in a new location. The original file remains unchanged.
Syntax:
bash
cp [options] source destination
Key Characteristics:
- Copies file content and optionally metadata
- By default, does not copy directories unless -r or -a is used
Common Options:
- -r or -R: Recursive copy for directories
- -p: Preserve metadata (timestamps, permissions)
- -u: Copy only if the source file is newer
- -a: Archive mode (recursive + preserve metadata + symlinks)
Examples:
- Copy a file: bash cp file.txt /tmp/
- Copy a directory recursively: bash cp -r src_folder/ backup_folder/
- Copy and preserve metadata: bash cp -p config.conf /etc/
Real-life use case:
Creating a full backup of configuration files before making changes:
bash
cp -a /etc/nginx /etc/nginx.bak
3. mkdir – Create Directories
The mkdir command creates new directories. It can also create nested directories when used with the -p option.
Syntax:
bash
mkdir [options] directory_name
Key Characteristics:
- Creates one or more directories
- Does not create parent directories unless -p is used
- Will throw an error if the directory exists (unless -p is used)
Common Options:
- -p: Create parent directories as needed
- -v: Print messages for each created directory
Examples:
- Create a single directory: bash mkdir logs
- Create nested directories: bash mkdir -p /var/www/html/images
- Create multiple directories at once: bash mkdir dir1 dir2 dir3
Real-life use case:
Before deploying a web app, a developer creates the necessary directory structure for logs and uploads:
bash
mkdir -p /var/www/app/{logs,uploads,tmp}
4. rmdir – Remove Empty Directories
The rmdir command is used to delete directories, but it only works if the directory is completely empty (no files or subdirectories inside).
Syntax:
bash
rmdir [options] directory_name
Key Characteristics:
- Only removes empty directories
- Will return an error if the directory is not empty
- Safer than rm -r because it prevents accidental data loss
Common Options:
- -p: Remove parent directories if they are also empty
Examples:
- Remove an empty directory: bash rmdir old_logs
- Remove nested empty directories: bash rmdir -p project/src/old/ This removes old, src, and project if all are empty.
Real-life use case:
After unzipping a project and cleaning up unused scaffolding:
bash
rmdir temp_files temp_output
5. ls – List Directory Contents
The ls command displays the contents of a directory. It can show file names, metadata, permissions, and more, depending on the options used.
Syntax:
bash
ls [options] [directory]
Key Characteristics:
- Default behavior shows filenames only
- Can be enhanced to show details like file size, modification date, ownership, and type
Common Options:
- -l: Long listing format (shows permissions, ownership, timestamps)
- -a: Show hidden files (files starting with .)
- -h: Human-readable sizes (used with -l)
- -R: Recursive listing (include subdirectories)
Examples:
- List all files, including hidden ones, with details: bash ls -la
- List contents of another directory: bash ls /etc/nginx/
- List files recursively: bash ls -R ~/projects/
Real-life use case:
A developer inspects the contents and permissions of a configuration directory:
bash
ls -lh /etc/apache2/
6. pwd – Print Working Directory
The pwd (Print Working Directory) command shows the absolute path of your current directory in the shell.
Syntax:
bash
pwd
Key Characteristics:
- Useful when navigating complex directory structures
- Shows the full path, starting from the root (/)
Example:
bash
pwd # Output: /home/user/projects/webapp
Real-life use case:
While writing a script or compiling code, a developer confirms they are in the correct source directory:
bash
CopyEdit
cd ~/dev/build
pwd
7. rm – Remove Files and Directories
The rm command is used to delete files and directories. Unlike rmdir, it does not require directories to be empty, and it can also be used to recursively remove directory trees.
Warning: rm is irreversible — use with caution.
Syntax:
bash
rm [options] target
Key Characteristics:
- Deletes files and directories permanently
- Does not move to trash/recycle bin
- Often combined with wildcards or recursion
Common Options:
- -r or --recursive: Remove directories and their contents
- -f: Force deletion (ignore nonexistent files and suppress warnings)
- -i: Prompt before every removal
- -v: Verbose output (list what's being removed)
Examples:
- Remove a single file: bash rm file.txt
- Remove a directory and its contents: bash rm -r logs/
- Force delete without confirmation: bash rm -rf /tmp/old_data/
Real-life use case:
Clearing old temporary files or log directories:
bash
rm -rf /var/tmp/build_cache
8. cd – Change Directory
The cd command (Change Directory) is used to navigate the filesystem. It allows the user to switch the shell’s current working directory.
Syntax:
bash
cd [directory_path]
Key Characteristics:
- If no argument is given, cd takes the user to their home directory
- Supports relative (cd ../folder) and absolute paths (cd /usr/local)
- Special variables:
~ → Home directory
- → Switch to the previous directory
- ~ → Home directory
- → Switch to the previous directory
Examples:
- Change to a specific directory: bash cd /etc/nginx/
- Return to the home directory: bash cd ~
- Go up one directory: bash cd ..
- Switch between last two directories: bash cd -
Real-life use case:
While managing multiple project directories:
bash
cd ~/projects/clientA/
9. . (Dot) – Current Directory or Execute in Current Shell
The . symbol has multiple meanings depending on context:
1. Current Directory Reference:
Used in paths or commands to refer to the current directory.
Examples:
- Run a script located in the current directory: bash ./script.sh
- Copy a file to the current directory: bash cp /etc/hosts .
2. Sourcing a File in the Current Shell:
Using a single dot (.) followed by a script file sources the script, executing its contents in the current shell session.
Equivalent to source:
bash
. env_setup.sh
This is useful when you want to export environment variables or modify the shell state without launching a subshell.
Real-life use cases:
- Running a local script: bash ./deploy.sh
- Loading environment variables from a file: bash . ~/.bash_profile
10. .. – Parent Directory
The .. symbol refers to the parent directory of the current working directory. It's used for relative navigation and is essential in scripts, automation, and terminal workflows.
Usage Examples:
- Move up one directory: bash cd ..
- Copy a file from the parent directory: bash cp ../config.json .
- Run a script from the parent directory: bash ../deploy.sh
Real-life use case:
You’re inside /home/user/projects/app/ and want to go back to /home/user/projects/:
bash
cd ..
11. ~ – Home Directory
The tilde ~ is a shortcut for the current user's home directory (e.g., /home/username or /root for the root user). It can be used in file paths and commands.
Usage Examples:
- Navigate to your home directory: bash cd ~
- Open a file in your home folder: bash nano ~/.bashrc
- Copy a file to another user’s home: bash cp data.txt ~john/
Real-life use case:
You want to edit your shell profile or environment variables:
bash
vim ~/.bash_profile
12. tree – Display Directory Structure as a Tree
The tree command visually displays the hierarchical structure of directories and files. It’s useful for getting a quick overview of nested folders and is commonly used in documentation and code reviews.
Key Characteristics:
- Recursively displays subdirectories and files in a tree-like format
- Shows file counts and depths
- Can be limited to specific depth levels
- Must be installed on some systems (sudo apt install tree or sudo yum install tree)
Syntax:
bash
tree [options] [directory]
Common Options:
- -L n: Limit to depth n
- -a: Include hidden files
- -d: Show directories only
- -f: Print full paths
Examples:
- Display current directory tree: bash tree
- Show only directories, up to 2 levels deep: bash tree -L 2 -d
- View full path of each item: bash tree -f
Real-life use case:
A developer shares a project structure in a README:
bash
tree -L 2
Output:
css
. ├── config │ └── settings.json ├── src │ ├── main.py │ └── utils.py └── README.md
13. cat – Concatenate and Display File Content
The cat command is short for concatenate. It's used to display the contents of files, combine multiple files into one, or redirect content into new files. It’s commonly used in both manual inspections and scripts.
Syntax:
bash
cat [options] filename(s)
Key Characteristics:
- Reads files sequentially and sends their content to stdout (screen)
- Can be used to display, create, or merge files
- Handles text and binary data, but typically used for text files
Common Options:
- -n: Number all output lines
- -b: Number non-blank lines only
- -s: Suppress repeated blank lines
Usage Examples:
- Display the content of a file: bash cat file.txt
- Combine two files into a new one: bash cat file1.txt file2.txt > merged.txt
- View a file with line numbers: bash cat -n script.sh
Real-life use case:
A developer quickly checks the output of a log file:
bash
cat /var/log/syslog | grep error
14. touch – Create Empty Files or Update Timestamps
The touch command is used to create new, empty files or update the access and modification timestamps of existing files. It is especially useful for scripting, creating placeholder files, or triggering timestamp-based workflows.
Syntax:
bash
touch [options] filename(s)
Key Characteristics:
- Creates a file if it doesn’t exist
- Updates access (atime) and modification (mtime) timestamps if it does
- Supports setting custom timestamps
Common Options:
- -c or --no-create: Do not create file if it doesn’t exist
- -t [[CC]YY]MMDDhhmm[.ss]: Set a custom timestamp
- -r file: Use another file’s timestamp
Usage Examples:
- Create an empty file: bash touch newfile.txt
- Update timestamp of an existing file: bash touch existing.log
- Create multiple files at once: bash touch file{1..3}.txt
- Set file timestamp to match another: bash touch -r reference.txt target.txt
Real-life use case:
A system admin creates a .lock file to indicate a service is running or locked:
bash
touch /var/run/myservice.lock