-
Notifications
You must be signed in to change notification settings - Fork 0
๐ง LINUX ADMINISTRATION
- Linux is the kernel of a family of open-source, Unix-like operating systems.
- It was created by Linus Torvalds in 1991 and has grown into one of the most influential open-source projects in history.
- Known for its stability, security, and versatility, Linux is used across servers, mainframes, embedded systems, and desktops.
- The kernel is the core component of any operating system.
- It acts as a bridge between hardware and software, managing:
- CPU scheduling
- Memory allocation
- Input/output (I/O) operations
- Process management
- The kernel ensures efficient and secure access to system resources.
- An Operating System is software that manages hardware and software resources.
- It includes:
- The kernel
- System libraries
- Utilities
- User interfaces (graphical shells or command-line interfaces)
- Unix is a multi-user, multitasking operating system developed in the 1970s at Bell Labs by Ken Thompson and Dennis Ritchie.
- Its modular designโkernel, shell, and utilitiesโformed the basis for Linux and many modern OSes.
GNU/Linux refers to a family of open-source operating systems combining:
- The Linux kernel, and
- The GNU Projectโs tools and libraries.
The GNU Project, initiated by Richard Stallman in 1983, provided essential user-space utilities, compilers, and libraries that make Linux a complete, functional system.
- Developed by Linus Torvalds (1991).
- Manages hardware resources, process scheduling, and system calls.
- Licensed under the GNU GPL, allowing modification and redistribution.
- Highly modular and supports a wide range of hardware (servers, phones, IoT devices).
- Provided by the Free Software Foundation (FSF) to complement the kernel.
- Key tools include:
-
GNU Coreutils โ Essential commands (
ls,cp,mv,rm). - GNU C Library (glibc) โ Interfaces programs with the kernel.
- GNU Compiler Collection (GCC) โ Compilers for C, C++, etc.
- Bash (Bourne Again Shell) โ Command-line interface.
-
GNU Coreutils โ Essential commands (
These tools enable core system tasks like file management, development, and administration.
- Desktop Environments: GNOME, KDE Plasma, XFCE.
-
Package Managers:
- Debian-based โ
apt - Red Hat-based โ
dnf/yum - Arch-based โ
pacman
- Debian-based โ
- Software Applications: Firefox, LibreOffice, Apache, Nginx, etc.
| Feature | Description |
|---|---|
| Open Source | Freely available and modifiable under the GNU GPL license. |
| Multitasking & Multiuser | Supports multiple users and processes simultaneously. |
| Stability | Reliable performance, ideal for servers and critical systems. |
| Security | Strong permissions and user privilege model. |
| Variety of Distributions | Many tailored variants for different needs (Ubuntu, Debian, Fedora, Arch). |
| Command Line Power | CLI provides efficiency and flexibility for advanced users. |
| Community Driven | Continuous improvement via global collaboration. |
A Linux distribution (distro) is a complete operating system built around the Linux kernel, bundled with:
- GNU tools and libraries
- A package manager
- Desktop environment or shell
- Pre-installed software and configurations
Each distribution serves different goals โ from ease of use to high security or minimalism.
- Linux Kernel โ Core of the system.
- GNU Software โ Shell, utilities, libraries.
- Package Manager โ Handles software installation and updates.
- Desktop Environment โ GUI (e.g., GNOME, KDE, XFCE).
- Applications โ Tools for daily use or development.
- Configuration Defaults โ Tailored usability and security settings.
| Category | Description | Examples |
|---|---|---|
| General-Purpose | Balanced for usability and functionality. | Ubuntu, Linux Mint, Fedora |
| Server-Focused | Optimized for performance and uptime. | Debian, CentOS Stream, Rocky Linux |
| Developer-Centric | Customizable and cutting-edge. | Fedora Workstation, Arch, Gentoo |
| Lightweight | For old or resource-limited systems. | Puppy Linux, Lubuntu, MX Linux |
| Security-Focused | Privacy and penetration testing. | Kali Linux, Tails, Qubes OS |
| Specialized | For specific fields (media, IoT, education). | Ubuntu Studio, Raspberry Pi OS |
| Type | Description | Example |
|---|---|---|
| Rolling Release | Continuous updates; always current. | Arch Linux, openSUSE Tumbleweed |
| Fixed Release | Stable versions released periodically. | Ubuntu, Debian |
- Debian-based; maintained by Canonical.
- Uses
aptpackage manager and GNOME desktop. - Regular releases + LTS versions every 2 years.
- Great for desktops, servers, and cloud environments.
- Renowned for stability and free software commitment.
- Offers Stable, Testing, and Unstable branches.
- Ideal for servers and users prioritizing reliability.
- Sponsored by Red Hat; cutting-edge and open-source focused.
- Frequent updates and innovative technologies (e.g., Wayland, PipeWire).
- Best for developers and tech enthusiasts.
- Minimalist, rolling-release model using
pacman. - Offers total control and customization.
- Includes the Arch User Repository (AUR) for extra packages.
- Ubuntu-based, user-friendly, and ideal for Windows migrants.
- Uses Cinnamon, XFCE, or MATE desktops.
- Comes with essential tools pre-installed.
- Enterprise-grade distros built for stability.
- CentOS Stream previews Red Hat updates.
- Rocky Linux offers binary compatibility with RHEL.
- Debian-based, for security testing and forensics.
- Bundled with tools like Metasploit, Nmap, and Burp Suite.
- Privacy-oriented; routes all traffic through Tor.
- Leaves no trace on host systems โ ideal for anonymity.
- Debian-based and optimized for Raspberry Pi hardware.
- Used for IoT, robotics, and education projects.
Linux architecture is composed of several key layers that work together to manage system resources and provide functionality.
- The core of the OS; manages CPU, memory, and device communication.
- Provides process isolation and hardware abstraction.
- Types of kernels:
- Monolithic
- Microkernel
- Hybrid
- Exokernel
- Precompiled shared code that provides system functionality.
- Acts as an interface between user applications and the kernel.
- Example: glibc, the GNU C Library.
- User interface for executing commands.
- Translates commands into system calls for the kernel.
- Examples: bash, zsh, fish.
- Physical components: CPU, RAM, Disk, Network, I/O devices.
- Interacts directly with the kernel and system libraries.
- Tools for configuration and management (e.g.,
top,ps,ifconfig,apt). - Used for installing software, managing users, and monitoring performance.
โ
Open Source โ Free to use, modify, and distribute.
โ
Secure โ Strong user permissions and minimal malware.
โ
Stable โ Rarely crashes or requires rebooting.
โ
Community Support โ Active developer and user base.
โ
Flexible โ Install only the components you need.
โ
Fast & Lightweight โ Runs efficiently even on older hardware.
โ
Privacy-Focused โ Protects user data and system integrity.
โ
Compatible โ Supports many file formats and hardware types.
โ
Frequent Updates โ Easy software and system upgrades.
Virtualization enables multiple operating systems to run simultaneously on one physical machine by creating virtual machines (VMs) โ isolated systems with their own CPU, memory, and storage.
It enhances:
- Resource utilization
- Isolation
- Scalability
- Flexibility
-
Hypervisor
- Software managing virtual machines.
- Type 1 (Bare-Metal): Runs directly on hardware (KVM, Xen, VMware ESXi).
- Type 2 (Hosted): Runs on a host OS (VirtualBox, VMware Workstation).
-
Virtual Machine
- A self-contained system with its own OS and applications.
- Operates independently from the host system.
-
Virtualization Technologies
- Full Virtualization: Complete hardware emulation (QEMU, VirtualBox).
- Paravirtualization: Requires OS modification for better performance (Xen).
- Containerization: Lightweight, shares the host kernel (Docker, Podman).
- ๐งช Development & Testing: Run multiple OSes for testing environments.
- ๐ฅ๏ธ Server Consolidation: Host many services on one machine.
- ๐ Isolation: Improve security and stability.
- ๐ Cross-Platform Use: Run Windows/macOS on Linux systems.
- โ๏ธ Cloud & DevOps: Power containerized and virtualized cloud infrastructures.
Popular Virtualization Tools:
- VirtualBox
- KVM (Kernel-based Virtual Machine)
- VMware
- QEMU
- Docker / Podman (for containers)
The Shell is a program that provides a text-based interface for users to communicate with the Linux kernel and run programs. It interprets user input, executes commands, and displays output.
It acts as an intermediary between the user, the Linux kernel, and system utilities โ either interactively (via terminal commands) or non-interactively (through scripts).
-
Command Execution: Runs commands like
ls,cp, orsudo apt update. - Scripting: Automates repetitive tasks using shell scripts.
-
Environment Management: Manages environment variables like
$PATHand$HOME. -
Input/Output Redirection: Redirects output (e.g.,
ls > files.txt) and enables piping (ls | grep txt). -
Job Control: Manages background/foreground processes (
bg,fg).
- Bourne Shell (sh): Original Unix shell (1977), simple but limited.
-
Bash (Bourne Again Shell): Most common shell; improved
shversion (default in many distros). - Z Shell (zsh): Enhanced features, great autocompletion, supports plugins (e.g., Oh My Zsh).
-
KornShell (ksh): Combines
shandcshfeatures, often used in enterprise systems. - C Shell (csh/tcsh): Syntax similar to C; less common today.
- Fish (Friendly Interactive Shell): Modern, user-friendly, colorful, and auto-suggestive.
-
Others:
dash(lightweight, scripting-focused) andxonsh(Python-based).
Used to navigate and manipulate files and directories.
-
lsโ List directory contents-
Usage:
ls,ls -l,ls -a -
Example:
ls -la
-
Usage:
-
cdโ Change directory-
Usage:
cd path/to/dir,cd ..,cd ~ -
Example:
cd /var/log
-
Usage:
-
pwdโ Print working directory-
Example:
pwd
-
Example:
-
mkdirโ Create directory-
Example:
mkdir my_folder
-
Example:
-
rmโ Remove files or directories-
Usage:
rm file,rm -r folder -
Example:
rm -r old_folder
-
Usage:
-
cpโ Copy files or directories-
Example:
cp document.txt backup/
-
Example:
-
mvโ Move or rename-
Example:
mv file.txt new_name.txt mv file.txt /tmp/
-
Example:
-
touchโ Create or update a file-
Example:
touch notes.txt
-
Example:
Used to view or modify file content.
-
catโ View file contentscat /etc/hosts
-
lessโ Scroll through filesless /var/log/syslog
-
nanoโ Simple text editornano script.sh
-
vimโ Advanced text editorvim config.txt
Used to monitor processes and resource usage.
-
topโ View system processestop
-
htopโ Enhanced process viewerhtop
-
dfโ Check disk spacedf -h
-
duโ Check directory sizesdu -sh /home/user
-
freeโ Check memory usagefree -h
Used for connectivity testing and network management.
-
pingโ Test network reachabilityping 8.8.8.8
-
curlโ Fetch data from URLscurl example.com
-
wgetโ Download fileswget https://example.com/file.iso
-
ipโ Manage network interfacesip addr show
Manage file and directory access.
-
chmodโ Change file permissionschmod +x script.sh
-
chownโ Change ownershipchown user:users document.txt
Control and terminate processes.
-
psโ List running processesps aux | grep bash -
killโ Terminate by PIDkill -9 1234
-
manโ Show manual pagesman ls
-
sudoโ Run commands as superusersudo apt update
-
clearโ Clear terminalclear
-
historyโ Show command historyhistory | grep apt
Paths define where files or directories are located in the filesystem.
- Starts from the root
/. - Example:
/home/user/documents/file.txt
- Based on current directory.
- Example:
./documents/file.txt
| Symbol | Meaning | Example |
|---|---|---|
. |
Current directory | ./script.sh |
.. |
Parent directory | cd .. |
~ |
Home directory | cd ~/Documents |
/ |
Root directory | ls / |
Linux user management involves creating, modifying, and deleting users and groups, controlling access, and managing permissions.
-
Users: Entities with accounts and UIDs (found in
/etc/passwd).- Root (UID 0): Full control.
- Regular Users: Limited access.
-
System Users: Service accounts (e.g.,
daemon,nobody).
-
Groups: Collections of users sharing permissions (
/etc/group). -
Permissions: Controlled by
chmod,chown, and displayed withls -l. -
Home Directories: Usually
/home/username. -
Configuration Files:
-
/etc/passwd,/etc/shadow,/etc/group,/etc/gshadow
-
-
Sudo: Allows privileged commands. Example:
sudo apt update
sudo useradd -m -s /bin/bash john
sudo adduser jane
sudo passwd johnsudo usermod -aG sudo jane
sudo chsh -s /bin/zsh johnsudo userdel -r john
sudo deluser --remove-home janesudo groupadd developers
sudo groupmod -n devteam developers
sudo groupdel developers
sudo gpasswd -a john devteamid john
whoami
groups john
cat /etc/passwd | grep john
cat /etc/group | grep devteamchmod 750 /home/john/data
chown john:developers /home/john/project- โ
Use
adduser(more user-friendly thanuseradd) - ๐ Enforce strong passwords (
passwd) - ๐ซ Limit root access; use
sudo - ๐ฅ Manage permissions via groups
- ๐งพ Regularly audit
/etc/passwdand/etc/group - ๐พ Backup home directories before deletion
- โ๏ธ Edit
/etc/sudoerssafely usingvisudo - ๐ง Use descriptive usernames and group names
Package management is the process of installing, updating, configuring, and removing software packages in Linux.
Different Linux distributions use different package managers to handle software packages and dependencies.
Package managers use repositories (remote servers) that store collections of packages.
These repositories can be official or third-party.
| Distribution | Package Manager | Command Examples |
|---|---|---|
| Ubuntu / Debian |
apt, dpkg
|
apt install, apt update, dpkg -i
|
| CentOS / RHEL / Fedora |
yum, dnf, rpm
|
yum install, dnf update, rpm -ivh
|
| Arch Linux | pacman |
pacman -S package |
| openSUSE | zypper |
zypper install package |
sudo apt install nginx
sudo yum install nginxsudo apt remove nginx
sudo yum remove nginxsudo apt update
sudo yum updatesudo apt upgrade
sudo yum upgradeapt search apache2
apt show apache2
yum info nginx
pacman -Qi nginxapt list --installed
yum list installedapt show nginx
yum info nginxsudo dpkg -i package.deb
sudo rpm -ivh package.rpmsudo apt --fix-broken installsudo apt clean
sudo yum clean allyum history
dnf historyUse APT (Advanced Package Tool).
sudo apt update # Refresh package index
sudo apt install nginx # Install a package
sudo apt remove nginx # Remove a package
sudo apt purge nginx # Remove package with config files
sudo apt upgrade # Upgrade all upgradable packages
sudo apt autoremove # Remove unused dependenciesUse YUM (or DNF for newer systems).
sudo yum install nginx
sudo yum remove nginx
sudo yum update
sudo yum search nginx
sudo yum list installedUse Pacman.
sudo pacman -Syu # Update and upgrade
sudo pacman -S nginx # Install
sudo pacman -R nginx # Remove
sudo pacman -Ss nginx # Search
sudo pacman -Q # List installed packagesFile management in Linux involves creating, viewing, editing, moving, copying, and deleting files and directories using command-line tools.
| Action | Command | Example |
|---|---|---|
| List files | ls |
ls -la |
| Change directory | cd |
cd /var/log |
| Print working directory | pwd |
pwd |
| Create a file | touch |
touch file.txt |
| View file contents |
cat, less, head, tail
|
cat file.txt |
| Copy files | cp |
cp file1 file2 |
| Move or rename | mv |
mv old new |
| Remove files | rm |
rm file.txt |
| Create directories | mkdir |
mkdir new_folder |
| Remove directories |
rmdir, rm -r
|
rm -r folder |
| View file type | file |
file data.bin |
touch file.txt # Create an empty filecat file.txt # View full file
less file.txt # Scroll through file
head -n 10 file.txt # View first 10 lines
tail -n 10 file.txt # View last 10 lines
tail -f logfile.log # Follow updates in real-timels -l # Long listing format
ls -lh # Human-readable sizes
ls -a # Show hidden files
ls -R # Recursive listing
file filename # Show file type
stat filename # Display file metadatanano file.txt
vi file.txt
vim file.txtcp file1 file2 # Copy file
cp file1 /dir/ # Copy to directory
cp -r dir1 dir2 # Copy directory recursivelymv file1 /dir/ # Move file
mv oldname.txt newname.txt # Rename filerm file.txt # Delete a file
rm -i file.txt # Prompt before deletingrmdir empty_dir # Remove empty directory
rm -r folder_name # Remove a directory recursively
rm -rf folder_name # Force removels -lchmod 755 script.sh
chmod u+x script.shchown user:group file.txt # Change owner and groupls -lh file.txtdu -sh *
df -hGlobbing allows you to use special characters (wildcards) to match multiple filenames in the shell.
| Wildcard | Description | Example |
|---|---|---|
* |
Matches any number of characters | ls *.txt |
? |
Matches a single character | ls file?.txt |
[ ] |
Matches any single character inside brackets | ls file[1-3].txt |
{ } |
Matches a comma-separated list of patterns | ls {file1,file2}.txt |
ls *.txtls file?.txtls file[1-5].txtls {notes,summary,report}.txtIf you want to prevent globbing, use quotes or backslashes.
ls "*.txt" # Treats *.txt as literal text
ls \*.txt # Escapes the asteriskText file management in Linux is a fundamental aspect of system administration, development, and everyday computing in GNU/Linux distributions.
-
Text files are ubiquitous in Linux, serving as:
- Configuration files (e.g.,
/etc/passwd) - Scripts (e.g.,
.shfiles) - Logs (e.g.,
/var/log/syslog) - Data storage (e.g.,
.csvor.txt)
- Configuration files (e.g.,
-
Linux provides a rich set of command-line tools for:
- Creating, viewing, editing, searching, manipulating, and comparing text files
- Emphasizing efficiency, automation, and precision
-
Text files are plain ASCII or UTF-8 encoded files containing human-readable content, without binary data or formatting (unlike
.docx). -
Linux treats text files as streams of characters, enabling powerful piping and redirection.
Example:command > file.txt # Redirect output to a file
-
Common Encodings: UTF-8 (default in modern distributions), ASCII.
Convert encodings usingiconv:iconv -f ISO-8859-1 -t UTF-8 file.txt > converted.txt -
Line Endings:
- Linux: LF (
\n) - Windows: CRLF (
\r\n) Convert formats usingdos2unix:
dos2unix file.txt
- Linux: LF (
-
Piping and Redirection is essential for text management:
-
>โ Overwrite -
>>โ Append -
<โ Input -
|โ Pipe output to another command
Example:
echo "Hello" > file.txt # Creates/overwrites file.txt cat file1.txt file2.txt > combined.txt # Concatenate files into one
-
Creating text files is straightforward, often involving redirection or text editors.
Used for creating simple text files.
echo "Line 1\nLine 2" > notes.txtCreates notes.txt with two lines.
Provides more precise formatting.
printf "Value: %d\n" 42 > data.txtCreates empty files or updates timestamps.
touch empty.txtCreates an empty file named empty.txt.
-
Usage:
nano file.txt
-
Shortcuts:
- Save โ
Ctrl + O - Exit โ
Ctrl + X - Search โ
Ctrl + W
- Save โ
-
Example:
Edit system hosts file (requires superuser privileges).
sudo nano /etc/hosts
-
Usage:
vim file.txt
-
Modes:
- Insert mode โ
i - Save & exit โ
:wq - Search โ
/pattern
- Insert mode โ
-
Advanced:
- Record macros โ
q - Customize via
.vimrc(e.g., syntax checking)
- Record macros โ
-
Example:
Edit a shell script and enable line numbers using
vim script.sh
:set number.
- Usage:
emacs file.txt- Shortcuts:
- Save โ
Ctrl + X, thenCtrl + S - Exit โ
Ctrl + X, thenCtrl + C - Features:
- Org-mode for structured text
- Integration with tools like Magit for Git
- vi โ Minimal version of Vim
- gedit โ GUI editor for GNOME
- kate โ GUI editor for KDE
Redirection allows you to change the default flow of data for a process.
Normally:
- Standard Input (stdin) โ comes from your keyboard
- Standard Output (stdout) โ goes to your screen (terminal)
- Standard Error (stderr) โ also goes to your screen
With redirection, you can reroute these data streams to or from files, devices, or other commands.
| Stream Name | File Descriptor | Default Device | Purpose |
|---|---|---|---|
| stdin | 0 |
Keyboard | Input to a program |
| stdout | 1 |
Terminal | Normal output |
| stderr | 2 |
Terminal | Error messages |
Send output to a file instead of the screen.
command > file.txt- Creates or overwrites
file.txtwith the output. - Example:
Saves the directory listing into
ls > list.txtlist.txt.
Append output to the end of a file instead of overwriting it.
command >> file.txt- Example:
echo "New entry" >> log.txt
Use a file as input to a command instead of the keyboard.
command < input.txt- Example:
sort < unsorted.txt
Send error messages to a file.
command 2> errors.txt- Example:
ls /fakepath 2> error.log
Send both normal output and errors to the same file.
command > all.log 2>&1or shorthand:
command &> all.log- Example:
find / -name "*.conf" > results.log 2>&1
Redirect output to /dev/null, a special device that discards data.
command > /dev/null 2>&1- Commonly used to run commands quietly.
A pipe connects the output of one command to the input of another.
command1 | command2- Example:
Sends the list of running processes into
ps aux | grep firefoxgrepto filter results.
You can chain multiple pipes:
cat /etc/passwd | grep bash | sortcommand > output.txt 2> error.txtcommand 3>&1 1>&2 2>&3(Advanced shell scripting use case)
Feed inline text as input to a command.
cat <<EOF
This is a
multiline text input
EOF| Task | Command |
|---|---|
Save output of ls
|
ls > files.txt |
| Append date to log | date >> log.txt |
| Suppress all output | command > /dev/null 2>&1 |
| Capture errors only | command 2> errors.log |
| Combine outputs | command > all.log 2>&1 |
| Chain commands | cat file.txt | grep keyword | sort |
| Symbol | Meaning |
|---|---|
> |
Redirect stdout (overwrite) |
>> |
Redirect stdout (append) |
< |
Redirect stdin |
2> |
Redirect stderr |
&> |
Redirect stdout and stderr together |
| ` | ` |
/dev/null |
Discard output |
Redirection in Linux = Controlling where data flows
(From โ Keyboard, To โ Screen, or vice versa โ Files, Programs, Devices)
Command chaining in Linux is a powerful technique that allows multiple commands to be executed sequentially, with the output of one command serving as the input to another. This approach enables elegant, efficient data processing pipelines that can transform raw data into actionable insights without intermediate files or complex scripting.
The Unix philosophy emphasizes building small, focused tools that do one thing well and can be combined to solve complex problems. Command chaining is the practical embodiment of this philosophy, enabling developers and system administrators to create sophisticated data processing workflows from simple, reusable components.
By chaining commands, users can:
- Execute complex workflows efficiently.
- Pass data between commands.
- Control execution flow based on success or failure.
- Create powerful one-liners for data manipulation.
The pipe operator takes the standard output (stdout) of one command and passes it as the standard input (stdin) to another command.
command1 | command2 | command3- Semicolon (;) โ Executes commands sequentially regardless of success or failure
command1 ; command2 ; command3
- Logical AND (&&) โ Executes the next command only if the previous succeeds
command1 && command2 && command3
- Logical OR (||) โ Executes the next command only if the previous fails
bash command1 || command2 || command3
(command1 ; command2) | command3๐งฐ Summary Table
| Operator | Description | Example |
|---|---|---|
; |
Executes commands sequentially, regardless of success or failure. | cmd1; cmd2 |
&& |
Executes the next command only if the previous succeeds. | cmd1 && cmd2 |
|| |
Executes the next command only if the previous fails. | cmd1 || cmd2 |
| |
Pipes output of one command as input to another. | cmd1 | cmd2 |
|& |
Pipes both stdout and stderr to next command. | cmd1 |& cmd2 |
& |
Runs a command in the background. | cmd1 & |
Used to search for text patterns within files or command outputs.
cat access.log | grep "ERROR"
grep -in "warning" system.log
grep -v "DEBUG" application.logUsed for find-and-replace, deleting, or selecting specific lines in text streams.
sed 's/old/new/' file.txt # Replace first occurrence per line
sed 's/old/new/g' file.txt # Replace all occurrences per line
sed '/^#/d' config.txt # Delete lines starting with '#'
sed -n '10,20p' data.txt # Print lines 10 to 20Used for structured text manipulation, field extraction, and computations.
awk '{print $1, $3}' data.txt # Print 1st and 3rd fields
awk '$2 > 100 {print $1, $2}' records.txt # Conditional printing
awk '{sum += $1} END {print sum}' numbers.txt # Sum all values in column 1
awk '$3 ~ /error/ {print}' logs.txt # Match pattern in 3rd fieldUsed to arrange lines in ascending, descending, or key-based order.
sort -n numbers.txt # Numeric sort
sort -r file.txt # Reverse sort
sort -k2 -n data.txt # Sort by 2nd column numerically
sort -u file.txt # Unique sort (remove duplicates)Filters out or counts duplicate lines (often used after sort).
uniq file.txt # Remove consecutive duplicates
uniq -c file.txt # Count occurrences
uniq -u file.txt # Show unique lines only
uniq -d file.txt # Show duplicate lines onlycat data.txt | grep "error" | sort | uniq -c | sort -nrExplanation:
-
cat data.txtโ Reads the contents of the file. -
grep "error"โ Filters lines containing โerrorโ. -
sortโ Sorts the filtered lines. -
uniq -cโ Counts unique occurrences. -
sort -nrโ Sorts numerically in reverse order.
Commands run one after another, regardless of success or failure.
echo "Starting process"; ls; echo "Process complete"-
&&runs the next command only if the previous succeeds. -
||runs the next command only if the previous fails.
mkdir reports && echo "Directory created successfully" || echo "Failed to create directory"Given a CSV file named sales.csv:
Region,Product,Sales
East,Phone,150
West,Laptop,200
East,Laptop,100
West,Phone,250
Extract and summarize sales by product:
cat sales.csv | tail -n +2 | cut -d',' -f2,3 | sort | \
awk -F',' '{arr[$1]+=$2} END {for (i in arr) print i, arr[i]}' | sort -k2 -nrOutput:
Phone 400
Laptop 300
cat data.txt | grep "SUCCESS" > success.log && echo "Success log updated" || echo "No successful entries found"- Saves matching lines to
success.log. - Prints a success message if matches are found, otherwise prints an error message.
Find the top 5 most frequent errors in system logs:
grep "ERROR" /var/log/syslog | cut -d' ' -f5- | sort | uniq -c | sort -nr | head -5Convert raw text data to uppercase, normalize spacing, and remove empty lines:
cat raw_data.txt | tr -d '\r' | sed 's/[[:space:]]\+/ /g' | grep -v '^$' | awk '{print toupper($0)}' > clean_data.txtRun multiple sorting jobs in parallel and wait for all to finish:
cat bigdata1.csv | sort > sorted1.csv &
cat bigdata2.csv | sort > sorted2.csv &
wait && echo "All sorting complete"Compress a file only if it exists:
[ -f analysis.txt ] && cat analysis.txt | gzip > analysis.gz || echo "File not found!"Environment variables are dynamic named values that affect the behavior of processes and the shell environment in Linux.
They store essential system information and user preferences โ such as the location of executables, default editor, user identity, and current working directory.
Environment variables are key to system configuration, shell scripting, and application execution.
| Type | Scope | Description |
|---|---|---|
| System-wide | Global | Available to all users and processes (e.g., /etc/environment, /etc/profile). |
| User-specific | Local | Defined for a single user (e.g., ~/.bashrc, ~/.bash_profile). |
| Session variables | Temporary | Exist only for the current shell session. |
| Variable | Description |
|---|---|
PATH |
Directories where executable programs are located |
HOME |
Path to the userโs home directory |
USER |
Current logged-in username |
SHELL |
Path to the userโs shell |
PWD |
Current working directory |
OLDPWD |
Previous working directory |
LANG |
System language and locale |
EDITOR |
Default text editor |
LOGNAME |
Name of the logged-in user |
MAIL |
Path to userโs mail directory |
TERM |
Terminal type |
HISTFILE |
Location of command history file |
HISTSIZE |
Number of commands stored in history |
printenv
env
setecho $PATH
echo $HOME
echo $SHELLecho "My current shell is: $SHELL"
echo "Logged in as: $USER"
echo "Home directory: $HOME"Variables defined in this way exist only until the terminal session is closed.
MY_NAME="Irvine"
export COUNTRY="Kenya"
echo $MY_NAME
echo $COUNTRYTo make variables available permanently, define them in shell configuration files.
Add to:
-
~/.bashrcor~/.bash_profile(for Bash) -
~/.zshrc(for Zsh)
Example:
export EDITOR="vim"
export PATH="$PATH:/opt/custom/bin"Apply changes immediately:
source ~/.bashrcAdd to:
/etc/environment/etc/profile/etc/bash.bashrc
Example:
PATH="$PATH:/usr/local/sbin"
export JAVA_HOME="/usr/lib/jvm/java-17-openjdk-amd64"unset MY_NAME
echo $MY_NAME # No outputEdit your ~/.bashrc or /etc/environment and delete the relevant line.
The PATH variable tells the shell where to search for executables.
export PATH=$PATH:/opt/tools/binAdd this line to ~/.bashrc:
export PATH="$PATH:/opt/tools/bin"Then reload:
source ~/.bashrcecho $PATH | tr ':' '\n'FOLDER="/var/log"
echo "Listing files in $FOLDER"
ls $FOLDERFIRST="Linux"
SECOND="Admin"
echo "$FIRST $SECOND"
# Output: Linux Adminecho ${EDITOR:-nano}
# Prints current EDITOR or defaults to 'nano' if not setWhen you run a new shell or script, variables must be exported to be accessible in child processes.
MY_VAR="Hello"
bash -c 'echo $MY_VAR' # No output (not exported)
export MY_VAR="Hello"
bash -c 'echo $MY_VAR' # Output: Hello| File | Scope | Description |
|---|---|---|
/etc/environment |
System-wide | Global variables for all sessions |
/etc/profile |
System-wide | Login shell initialization |
/etc/bash.bashrc |
System-wide | Interactive shell configuration |
~/.bash_profile |
User-specific | Executed at login |
~/.bashrc |
User-specific | Executed for interactive non-login shells |
~/.profile |
User-specific | Legacy file for login shells |
Suppose you want to set up a development environment with Java and Python paths.
1๏ธโฃ Edit your ~/.bashrc:
export JAVA_HOME="/usr/lib/jvm/java-17-openjdk-amd64"
export PYTHONPATH="$HOME/projects/lib"
export PATH="$PATH:$JAVA_HOME/bin:$PYTHONPATH"2๏ธโฃ Reload your configuration:
source ~/.bashrc3๏ธโฃ Verify:
echo $JAVA_HOME
echo $PYTHONPATH
which java
which python3- Always use export for variables needed by subprocesses.
- Avoid overwriting critical variables like
$PATHโ always append or prepend instead. - Use lowercase for temporary or script-only variables (
temp_dir="/tmp"). - Use uppercase for environment-wide variables (
PATH,EDITOR,JAVA_HOME). - Quote variable values containing spaces (
export GREETING="Hello World"). - Reload your configuration after changes:
source ~/.bashrc
#!/bin/bash
echo "User: $USER"
echo "Home Directory: $HOME"
echo "Current Shell: $SHELL"
echo "PATH: $PATH"bash env_test.shUser: irvine
Home Directory: /home/irvine
Current Shell: /bin/bash
PATH: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin