removed space from dir names

This commit is contained in:
2026-04-10 23:52:56 +03:30
parent 9c419f72c4
commit ded4f55fb8
43 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,84 @@
# 🐧 Linux Runlevels Guide
This guide provides a concise overview of traditional **runlevels** in Linux systems, particularly for **Red Hat** and **Debian**-based distributions. Runlevels define specific states of system operation, historically managed by the `init` system.
---
## 🔄 System Boot Sequence
```plaintext
BIOS → Bootloader → Kernel → init
```
* **BIOS**: Performs hardware checks via **POST** (Power-On Self Test).
* **Bootloader**: Loads the kernel.
* **Kernel**: Initializes system and mounts the root filesystem.
* **init**: Launches system processes based on the selected runlevel.
---
## 📊 Runlevels Comparison
| Runlevel | Description | Red Hat | Debian |
| -------- | ----------------------------------- | ---------------- | --------------- |
| 0 | Halt / Shutdown | ✅ Supported | ✅ Supported |
| 1 | Single-User Mode | ✅ Supported | ✅ Supported |
| 2 | Multi-User (No Network) | ❌ (Includes Net) | ✅ Supported |
| 3 | Multi-User (Network, No GUI) | ✅ Supported | ✅ Supported |
| 4 | User-Defined / Custom | ✅ Supported | ✅ Supported |
| 5 | GUI Mode / *(Halt on some systems)* | ✅ GUI Mode | ⚠️ Custom/Halt? |
| 6 | Reboot | ✅ Supported | ✅ Supported |
> 💡 **Notes**:
> • **Runlevel 5** on Red Hat typically launches a full graphical environment (GUI).
> • On Debian, runlevels 25 are often configured identically and can be customized.
> • Runlevel behavior is configurable via `/etc/inittab` (SysVinit systems).
---
## 🔧 Useful Commands
### ✅ Check Current Runlevel
```bash
runlevel
```
### 🔁 Change Runlevel
```bash
telinit <runlevel>
```
or
```bash
init <runlevel>
```
> ⚠️ **Caution**: Switching runlevels may stop services or terminate user sessions. Use carefully on production systems.
---
## 🚀 Modern Systems: systemd Targets
Most modern Linux distributions use **systemd**, which replaces runlevels with **targets**.
| Runlevel | systemd Target |
| -------- | ------------------- |
| 0 | `poweroff.target` |
| 1 | `rescue.target` |
| 3 | `multi-user.target` |
| 5 | `graphical.target` |
| 6 | `reboot.target` |
### 📌 Common systemd Commands
```bash
# Show default target
systemctl get-default
# Change to graphical mode
systemctl isolate graphical.target
```

View File

@@ -0,0 +1,59 @@
# 📁 Linux Directory Structure & Basic Commands
This document provides an overview of important Linux directories, their types, and essential file management commands.
---
## 📂 Directory Types
| Type | Description |
| ----------- | ----------------------------------------------------------------------------------- |
| **Virtual** | Do not reside on disk; dynamically generated by the system (e.g., `/proc`, `/sys`). |
| **Normal** | Standard directories that store files and data on disk. |
---
## 🗂️ Common Linux Directories
| Directory | Type | Description |
| --------- | ------- | ----------------------------------------------------------- |
| `/etc` | Normal | System configuration files |
| `/opt` | Normal | Optional or third-party software packages |
| `/bin` | Normal | Essential binary executables for all users |
| `/sbin` | Normal | System binaries, typically for administrative tasks |
| `/lib` | Normal | Shared libraries and kernel modules |
| `/home` | Normal | User home directories |
| `/proc` | Virtual | Kernel and process information (virtual files) |
| `/srv` | Normal | Data for services provided by the system (e.g., web, FTP) |
| `/sys` | Virtual | Kernel devices and system information |
| `/usr` | Normal | Secondary hierarchy: programs, libraries, and documentation |
| `/var` | Normal | Variable data: logs, mail, print spool, temporary files |
| `/dev` | Virtual | Device files (e.g., disk, USB, terminals) |
| `/mnt` | Normal | Mount point for temporary filesystems |
| `/boot` | Normal | Boot loader files, kernel images |
---
## 🛠️ Basic File & Directory Commands
| Command | Description |
| ------- | ---------------------------------------- |
| `cd` | Change directory |
| `ls` | List directory contents |
| `rm` | Remove files or directories |
| `mkdir` | Create a new directory |
| `touch` | Create an empty file or update timestamp |
| `cp` | Copy files or directories |
| `mv` | Move or rename files or directories |
### 📘 Examples
```bash
cd /etc # Navigate to /etc directory
ls -l # List files in long format
rm file.txt # Delete file.txt
mkdir new_folder # Create a directory named 'new_folder'
touch file.txt # Create a new empty file
cp file1.txt file2.txt # Copy file1.txt to file2.txt
mv file.txt /home/user/ # Move file.txt to another directory
```

View File

@@ -0,0 +1,49 @@
# 📦 Linux Libraries & Package Management
This guide provides a quick overview of **library types**, **package sources**, and **Debian-based package management** commands using `apt`.
---
## 📚 Library Types
Linux supports two main types of libraries:
1. **Static Libraries (`.a`)**
- Linked at **compile-time**
- Included in the final binary
- Larger file size, faster execution
2. **Shared Libraries (`.so`)**
- Linked at **run-time**
- Saved separately from the binary
- Saves space and allows updates without recompiling
---
## 📦 Package Sources
### ✅ Official Packages
Provided and maintained by the distribution (e.g., Debian, Ubuntu, Red Hat).
### 🌐 Third-Party Packages
Created by external developers or organizations. Use with caution and verify trustworthiness.
---
## 🏬 Linux Package Managers
### 📦 Debian-based Systems
- **Package Manager**: `apt`
- **Low-level Tool**: `dpkg`
- **Package Format**: `.deb`
### 📦 Red Hat-based Systems
- **Package Manager**: `yum` or `dnf` (newer)
- **Low-level Tool**: `rpm`
- **Package Format**: `.rpm`
---
## 🌍 Package Mirrors
Mirrors are alternative download sources for package repositories, often closer geographically for faster updates.

View File

@@ -0,0 +1,94 @@
# 📦 `dpkg` Debian Package Manager
`dpkg` is the package manager for Debian-based Linux distributions. It is used to install, remove, and manage `.deb` packages directly.
### 📘 Basic Syntax
```bash
dpkg [<option>...] <command>
```
---
## 🌐 Finding Packages
You can browse and search for Debian packages at [pkgs.org](https://pkgs.org).
---
## 📋 Listing Installed Packages
```bash
dpkg -l
dpkg --list
```
---
## 📥 Installing a Package
```bash
dpkg -i <package.deb>
dpkg --install <package.deb>
```
> ⚠️ If there are missing dependencies, run:
```bash
apt install -f
```
---
## 📂 Viewing Package Contents
```bash
dpkg -c <package.deb>
dpkg --contents <package.deb>
```
---
## Getting Package Info
```bash
dpkg -I <package.deb>
dpkg --info <package.deb>
```
---
## 📁 Listing Installed Files
```bash
dpkg -L <package-name>
dpkg --listfiles <package-name>
```
---
## 🧹 Removing a Package (and its config files)
```bash
dpkg -p <package-name>
dpkg --purge <package-name>
```
---
## 📝 Checking Package Status
```bash
dpkg -s <package-name>
dpkg --status <package-name>
```
---
## 🔧 Reconfiguring a Package
```bash
dpkg-reconfigure <package-name>
```

View File

@@ -0,0 +1,148 @@
# 📦 Managing Packages with `apt` on Debian/Ubuntu
The `apt` (Advanced Package Tool) command-line utility allows you to manage software on Debian-based Linux systems. Below are essential `apt` commands grouped by purpose, with clear explanations for each.
---
## 🔄 1. Updating and Upgrading the System
### `sudo apt update`
Fetches the latest package lists from repositories. This ensures your system is aware of the newest available versions of packages.
```bash
sudo apt update
```
---
### `apt upgrade`
Installs the newest versions of all installed packages based on the updated package lists. It does **not** remove or install any other packages.
```bash
apt upgrade
```
---
## 🔍 2. Searching and Viewing Packages
### `apt show <package>`
Displays detailed information about a specific package, including version, dependencies, description, and more.
```bash
apt show <package>
```
---
### `apt list`
Lists packages based on various filters (e.g., installed, upgradable, available). Running it without arguments shows all packages.
```bash
apt list
```
---
### `apt-cache search <pkg name>`
Searches the package cache for packages matching the given name or description. Useful for discovering packages related to a topic or function.
```bash
apt-cache search <pkg name>
```
---
## 📥 3. Installing and Reinstalling Packages
### `apt install <pkg name>`
Installs a package and its dependencies from the repositories.
```bash
apt install <pkg name>
```
---
### `apt reinstall <package>`
Reinstalls the specified package. This is useful if files from a package are accidentally deleted or corrupted.
```bash
apt reinstall <package>
```
---
## ❌ 4. Removing Packages
### `apt remove <package>`
Removes the specified package but **retains configuration files**. Useful when planning to reinstall later without losing settings.
```bash
apt remove <package>
```
---
### `apt purge <package>`
Completely removes the package **along with its configuration files**. Use when you want a clean uninstallation.
```bash
apt purge <package>
```
---
### `apt autoremove`
Automatically removes packages that were installed as dependencies but are no longer needed.
```bash
apt autoremove
```
---
## 🛠️ 5. Advanced Package Handling
### `apt install -f`
Attempts to **fix broken dependencies** by installing missing packages. Often used after a failed install.
```bash
apt install -f
```
---
### `apt install --download-only <package>`
Downloads a package without installing it. The downloaded `.deb` files are saved in:
```bash
/var/cache/apt/archives/
```
Example:
```bash
apt install --download-only <package>
```
---
## ✅ Final Notes
* Always start with `sudo apt update` before any install or upgrade.
* Use `apt-cache search` when unsure of a packages exact name.
* Be cautious with `purge` as it deletes config files too.

View File

@@ -0,0 +1,156 @@
# 🍽️ Managing Packages with `yum` on RHEL/CentOS
`yum` (Yellowdog Updater, Modified) is the traditional package manager for RPM-based Linux distributions such as **Red Hat Enterprise Linux (RHEL)** and **CentOS**. Below is a breakdown of commonly used `yum` commands, categorized and explained in detail.
---
## 🔄 1. Updating the System
### `yum update`
Fetches the latest package metadata and installs available updates for all packages currently installed on the system.
```bash
yum update
```
---
### `yum upgrade`
Performs the same function as `yum update`. In older versions of `yum`, `upgrade` was used for more aggressive upgrades, but in recent versions, they are functionally equivalent.
```bash
yum upgrade
```
---
## 📥 2. Installing and Reinstalling Packages
### `yum install <pkg-name>`
Installs a new package along with any required dependencies.
```bash
yum install <pkg-name>
```
---
### `yum reinstall <pkg-name>`
Reinstalls an already installed package, which is useful if system files have been corrupted or modified.
```bash
yum reinstall <pkg-name>
```
---
### `yum localinstall <file-dir>`
Installs a `.rpm` package from a local file path while resolving dependencies using remote repositories.
```bash
yum localinstall <file-dir>
```
---
## ❌ 3. Removing Packages
### `yum remove <pkg-name>`
Uninstalls the specified package from the system, including any dependencies no longer required.
```bash
yum remove <pkg-name>
```
---
## 🔍 4. Querying and Searching
### `yum list`
Lists all available, installed, and updatable packages.
```bash
yum list
```
---
### `yum info <pkg>`
Displays detailed information about the specified package, including version, repository, summary, and description.
```bash
yum info <pkg>
```
---
### `yum search`
Searches for a keyword in package names and descriptions. Add the search term to complete the command.
```bash
yum search <keyword>
```
Example:
```bash
yum search python
```
---
### `yum deplist <pkg>`
Shows the list of dependencies for a given package.
```bash
yum deplist <pkg>
```
---
## 🕓 5. Package History and Transactions
### `yum history`
Displays a history of all yum transactions (installs, updates, removals), which can be reviewed or undone if needed.
```bash
yum history
```
---
## 💾 6. Downloading Packages (Without Installing)
### `yum download <pkg>`
Downloads an RPM package file without installing it. Useful for transferring or offline installations. Requires the `yum-utils` package.
```bash
yum download <pkg>
```
> 💡 **Note:** If you get an error, try installing `yum-utils`:
>
> ```bash
> yum install yum-utils
> ```
---
## ✅ Final Notes
* `yum` has been replaced by `dnf` in newer distributions (e.g., RHEL 8+), but still widely used in older systems.
* Always run `yum update` before installing new packages.
* Combine with `yum history` to review or undo changes when troubleshooting.

View File

@@ -0,0 +1,172 @@
# 📦 Managing Packages with `rpm` on RHEL/CentOS
The `rpm` command (RPM Package Manager) is the **low-level package management tool** used on **Red Hat-based** systems such as RHEL, CentOS, Fedora, and others. Unlike `yum`, `rpm` does not resolve dependencies automatically and is best used for advanced or manual package management.
Below are the core `rpm` commands categorized and explained.
---
## 📥 1. Installing Packages
### `rpm -i <file.rpm>`
### `rpm --install <file.rpm>`
Installs a new `.rpm` package file. This command will **fail if the package's dependencies are not already installed**.
```bash
rpm -i <file.rpm>
```
or
```bash
rpm --install <file.rpm>
```
> 💡 Tip: Use `yum localinstall` or `dnf install` instead for dependency resolution.
---
## 🔄 2. Upgrading Packages
### `rpm -U <file.rpm>`
### `rpm --upgrade <file.rpm>`
Upgrades an existing package if it is already installed. If the package is not already present, this command will install it.
```bash
rpm -U <file.rpm>
```
or
```bash
rpm --upgrade <file.rpm>
```
---
## ❌ 3. Removing Packages
### `rpm -e <package>`
### `rpm --erase <package>`
Removes a package from the system by name (not the filename). Note that this command also does **not resolve dependencies**, so it may break things if you're not careful.
```bash
rpm -e <package>
```
or
```bash
rpm --erase <package>
```
> ⚠️ Caution: Always check what depends on a package before removing it.
---
## 🔍 4. Querying Packages
### `rpm -q <package>`
Query whether a package is installed, and show its version.
```bash
rpm -q <package>
```
---
### `rpm -qa`
List **all installed packages**.
```bash
rpm -qa
```
---
### `rpm -qi <package>`
Displays detailed **information** about a specific installed package.
```bash
rpm -qi <package>
```
---
### `rpm -ql <package>`
Lists all files installed by a package.
```bash
rpm -ql <package>
```
---
### `rpm -qf <file>`
Finds out **which package** owns a specific file.
```bash
rpm -qf /usr/bin/wget
```
---
### `rpm -qp <file.rpm>`
Query a package file (without installing it) to see its metadata.
```bash
rpm -qp <file.rpm>
```
---
### `rpm -K <file.rpm>`
Verifies the **signature and integrity** of an RPM package file.
```bash
rpm -K <file.rpm>
```
---
## 🛠️ 5. Verifying and Checking
### `rpm -V <package>`
Verifies installed package files against their original metadata (modifications, corruption, etc.).
```bash
rpm -V <package>
```
---
### `rpm --test -i <file.rpm>`
Simulates an install without actually installing the package — useful for testing.
```bash
rpm --test -i <file.rpm>
```
---
## ✅ Final Notes
* `rpm` is a **powerful low-level tool**, but not recommended for resolving dependencies.
* For **automated dependency handling**, prefer using `yum` or `dnf`.
* Use `rpm` when you need precise control over the package management process or are working with standalone `.rpm` files.

View File

@@ -0,0 +1,114 @@
# 🔐 Secure Shell (SSH) Remote Access & Management
**SSH (Secure Shell)** is a cryptographic network protocol that allows users to **securely access and control remote machines** over a network. It's a foundational tool for system administrators, developers, and anyone managing remote systems.
---
## 🧠 What SSH Does
* **🔒 Encrypts Communication**
All data transmitted between the client and the remote server is encrypted, protecting it from eavesdropping and man-in-the-middle attacks.
* **🧑‍💻 Authenticates Users**
Supports both password-based and public key-based authentication to ensure that only authorized users gain access.
* **💻 Enables Remote Command Execution**
Run commands on a remote machine as if you're using its terminal directly.
* **📁 Supports Secure File Transfers**
Tools like `scp` (Secure Copy) and `sftp` (SSH File Transfer Protocol) allow encrypted file transfers between machines.
---
## 🚀 Installing the SSH Server
To accept SSH connections on a machine, you must install and start the **OpenSSH server**.
### On Debian/Ubuntu systems
```bash
sudo apt install openssh-server
```
* This installs the OpenSSH daemon (`sshd`), which listens for incoming SSH connections.
* To enable and start the service:
```bash
sudo systemctl enable ssh
sudo systemctl start ssh
```
---
### On RHEL/CentOS systems
```bash
sudo yum install openssh-server
```
* Start and enable the SSH service:
```bash
sudo systemctl enable sshd
sudo systemctl start sshd
```
---
## 🛠️ Common SSH Usage Examples
### 🔗 Connect to a Remote Server
```bash
ssh username@remote_host
```
### 📁 Copy a File to a Remote Server Using `scp`
```bash
scp file.txt user@remote_host:/path/to/destination/
```
### 📥 Copy a File from a Remote Server
```bash
scp user@remote_host:/path/to/file.txt .
```
### 🗂️ Use Interactive File Transfer with `sftp`
```bash
sftp user@remote_host
```
---
## 🔐 Key-Based Authentication (Optional but Recommended)
To use SSH without typing a password every time, you can set up key-based authentication:
1. **Generate SSH key pair on your local machine:**
```bash
ssh-keygen
```
2. **Copy the public key to the remote server:**
```bash
ssh-copy-id user@remote_host
```
3. Now you can SSH without a password prompt:
```bash
ssh user@remote_host
```
---
## ✅ Final Notes
* SSH is a vital tool for managing servers securely.
* Always **disable root login** and **use key authentication** for better security.
* You can configure SSH behavior in `/etc/ssh/sshd_config`.

View File

@@ -0,0 +1,119 @@
# Getting Started with Vim 📝
## 1. Installing Vim
To install Vim on a Debianbased system (like Ubuntu), run:
```bash
sudo apt update
sudo apt install vim
```
---
## 2. Opening Files or Directories
* **Open a file**
```bash
vim <filename>
```
* **Open a directory**
```bash
vim <directory_name>
```
(This opens Vims file browser—helpful for navigating and editing multiple files.)
---
## 3. Vim Modes
Vim works in multiple modes—here are the core ones:
1. **Normal mode** The default mode; used for navigation and commands.
2. **Insert mode** For editing text; enter it by pressing `i`, `a`, or `o`.
3. **Visual mode** For selecting text; enter it with `v`, `V`, or `Ctrl+v`.
---
## 4. Essential Commands
(Type these in **Normal mode** and then press Enter when needed)
| Command | Description |
| ----------- | ----------------------------------------- |
| `:w` | Save (write changes to the current file) |
| `:w <name>` | Save changes to a specified file `<name>` |
| `:wq` | Save and quit Vim |
| `:q` | Quit (only if no unsaved changes exist) |
| `:q!` | Quit without saving (discard all changes) |
---
## 5. Handy Shortcuts
These are core shortcuts used in **Normal mode**:
| Shortcut | Action |
| -------- | -------------------------------- |
| `dd` | Delete (cut) the current line |
| `yy` | Yank (copy) the current line |
| `p` | Paste after the cursor |
| `u` | Undo the last change |
| `gg` | Go to the first line of the file |
---
## 6. Quick Usage Flow
1. **Start Vim**:
```bash
vim example.txt
```
2. **Insert text**:
Press `i` → type your content → press `Esc` to return to **Normal mode**.
3. **Save your work**:
Type `:w` in Normal mode and press Enter.
4. **Make edits**:
* Use `dd` to delete a line
* Use `yy` to copy (yank) a line
* Move the cursor to a new location, then hit `p` to paste
* Press `u` to undo any mistake
5. **Navigate quickly**:
* `gg` to jump to the beginning
* Use arrow keys or `h`, `j`, `k`, `l` for navigation
6. **Finish editing**:
* `:wq` to save and exit
* `:q!` to exit without saving
---
## 7. Tips & Tricks
* **Visual mode**:
Press `v` to start selecting character by character, `V` for line selection, or `Ctrl+v` for block-wise selection.
* **Other navigation**:
* Use `G` to go to the end of the file
* Use a number before a command, e.g., `5dd` deletes 5 lines
---
### Summary
Vim may feel different at first, but once you get comfortable switching between **Insert**, **Normal**, and **Visual** modes, you'll find its a powerful and efficient editor.
Happy Vimming! 😊

View File

@@ -0,0 +1,70 @@
# 🗜️ ZIP Compression Cheatsheet
The `zip` command is a widely used tool for compressing files and folders into a `.zip` archive. It is cross-platform and supports features like encryption and customizable compression levels.
---
## 📦 Basic Syntax
```bash
zip [options] archive.zip files
```
---
## 🔧 Create a ZIP Archive
```bash
zip archive.zip file1 file2
```
* Compresses `file1` and `file2` into `archive.zip`
---
## 📈 Maximum Compression
```bash
zip -9 archive.zip file1 file2
```
* `-9`: Use maximum compression (slower, but smaller file size)
---
## 🔐 Create a Password-Protected ZIP
```bash
zip -e archive.zip file1 file2
```
* `-e`: Prompts for password encryption on the archive
---
## 📋 List Files in a ZIP Archive
```bash
unzip -l archive.zip
```
* `-l`: Lists contents of the ZIP without extracting
---
## 📂 Extract ZIP Archive
```bash
unzip archive.zip
```
* Extracts contents into the current directory
### 📁 Extract to Custom Directory
```bash
unzip archive.zip -d <custom-dir>
```
* `-d <custom-dir>`: Extracts files into the specified folder

View File

@@ -0,0 +1,155 @@
# Linux Compression & Archiving Cheatsheet
## Tar Command Basics
The `tar` command is used to create, extract, and manage archive files.
**Syntax:**
```bash
tar [options] [archive_name.tar] [file(s)/directory]
```
---
### Create a `.tar` Archive
```bash
tar -cf archive_file.tar file1 file2 dir1
```
**Options:**
* `-c`: Create a new archive
* `-f`: Specify the archive file name
### Create with Verbose Output
```bash
tar -cvf archive_file.tar file1 file2 dir1
```
* `-v`: Verbose mode (shows progress)
### Extract a `.tar` Archive
```bash
tar -xf archive_file.tar
```
or
```bash
tar -xvf archive_file.tar
```
* `-x`: Extract files
---
## Gzip Compression
**Gzip** (GNU zip) is a fast and widely used compression tool.
### Create a `.tar.gz` Archive
```bash
tar -czf archive_file.tar.gz file1 file2 dir1
```
* `-z`: Compress using gzip
### Verbose Creation
```bash
tar -czvf archive_file.tar.gz file1 file2 dir1
```
### Extract `.tar.gz`
```bash
tar -xzf archive_file.tar.gz
```
or
```bash
tar -xzvf archive_file.tar.gz
```
---
## Bzip2 Compression
**Bzip2** provides better compression than gzip but at the cost of speed.
### Create a `.tar.bz2` Archive
```bash
tar -cjf archive_file.tar.bz2 file1 file2 dir1
```
* `-j`: Compress using bzip2
### Verbose Creation
```bash
tar -cjvf archive_file.tar.bz2 file1 file2 dir1
```
### Extract `.tar.bz2`
```bash
tar -xjf archive_file.tar.bz2
```
or
```bash
tar -xjvf archive_file.tar.bz2
```
---
## XZ Compression
**XZ** offers the best compression ratio but is the slowest option.
### Create a `.tar.xz` Archive
```bash
tar -cJf archive_file.tar.xz file1 file2 dir1
```
* `-J`: Compress using xz
### Verbose Creation
```bash
tar -cJvf archive_file.tar.xz file1 file2 dir1
```
### Extract `.tar.xz`
```bash
tar -xJf archive_file.tar.xz
```
or
```bash
tar -xJvf archive_file.tar.xz
```
---
## Compression Format Comparison
| Feature | gzip | bzip2 | xz |
| ------------------- | ----------- | ---------- | --------- |
| Compression Speed | Fast | Slow | Slowest |
| Decompression Speed | Fast | Slower | Moderate |
| Compression Ratio | Good | Better | Best |
| File Extension | `.tar.gz` | `.tar.bz2` | `.tar.xz` |
| Common Use | General/Web | Backups | Archival |

View File

@@ -0,0 +1,85 @@
# 📘 **Using `grep` in Linux/Unix**
`grep` (Global Regular Expression Print) is a powerful command-line utility used to search for text patterns in files. Below are common variations of the `grep` command with examples and explanations.
---
## 🔍 Basic Search
```bash
grep "hello" file1
```
**Description**:
Searches for lines containing the word `hello` in `file1`. The search is **case-sensitive**.
---
## 🔍 Case-Insensitive Search
```bash
grep -i "hello" file1
```
**Description**:
Performs a **case-insensitive** search for `hello` in `file1`. Matches `hello`, `Hello`, `HELLO`, etc.
---
## 🔢 Show Line Numbers
```bash
grep -n "hello" file1
```
**Description**:
Displays matching lines **with their line numbers**.
---
## 🔢 Case-Insensitive with Line Numbers
```bash
grep -in "hello" file1
```
**Description**:
Combines `-i` and `-n` to show line numbers and ignore case.
---
## 🚫 Invert Match
```bash
grep -v "hello" file1
```
**Description**:
Shows lines that **do NOT** contain the word `hello`.
---
## 🚫 Invert, Ignore Case, and Show Line Numbers
```bash
grep -ivn "hello" file1
```
**Description**:
Combines all the above:
* `-i`: Ignore case
* `-v`: Invert match
* `-n`: Show line numbers
Shows all lines that **dont contain** `hello`, regardless of case, and includes line numbers.
---
## ✅ Summary of Flags
| Flag | Description |
| ---- | -------------------------- |
| `-i` | Ignore case |
| `-n` | Show line numbers |
| `-v` | Invert the match (exclude) |

View File

@@ -0,0 +1,45 @@
# 📘 **Using `less` in Linux/Unix**
`less` is a terminal pager program used to view the content of files one screen at a time. It's especially useful for viewing large files or logs.
---
## 📂 Basic Usage
```bash
less file
```
**Description**:
Opens `file` for viewing.
```bash
less /var/log/syslog
```
**Description**:
Opens the system log file for reading. Useful for examining system logs line by line.
---
## ⌨️ Common Keyboard Shortcuts
Here are the most frequently used keyboard shortcuts when using `less`:
| Key/Command | Action |
| ----------- | ------------------------------------ |
| `space` | Scroll **down** one screen |
| `b` | Scroll **up** one screen |
| `q` | **Quit** `less` |
| `/pattern` | **Search** forward for `pattern` |
| `n` | Go to the **next** match of pattern |
| `N` | Go to the **previous** match |
| `g` | Go to the **first line** of the file |
| `G` | Go to the **last line** of the file |
---
## ✅ Summary
`less` is a vital tool for system administrators, developers, and anyone dealing with large text files. With simple navigation and powerful search capabilities, it makes file reading efficient and user-friendly.

View File

@@ -0,0 +1,77 @@
# 📘 **Using `head` and `tail` Commands in Linux/Unix**
Both `head` and `tail` are essential commands for viewing specific portions of a file quickly, without opening the entire file.
---
## 🔝 `head` — Show the Top of a File
The `head` command displays the beginning part of a file.
### Syntax
```bash
head [options] file
```
### Examples
```bash
head file1
```
**Description**:
Displays the first 10 lines of `file1` (default behavior).
```bash
head -n 5 file1
```
**Description**:
Shows the first 5 lines of `file1`.
---
## 🔚 `tail` — Show the Bottom of a File
The `tail` command displays the end part of a file.
### Syntax
```bash
tail [options] file
```
### Examples
```bash
tail file1
```
**Description**:
Displays the last 10 lines of `file1` (default behavior).
```bash
tail -n 20 file1
```
**Description**:
Shows the last 20 lines of `file1`.
```bash
tail -f file1
```
**Description**:
Follows the file as it grows — useful for watching logs in real-time.
---
## ✅ Summary of Options
| Command | Option | Description |
| ------- | ------------- | ------------------------------------------- |
| `head` | `-n <number>` | Show the first `<number>` lines |
| `tail` | `-n <number>` | Show the last `<number>` lines |
| `tail` | `-f` | Follow the file in real-time (live updates) |

View File

@@ -0,0 +1,52 @@
# 📘 **Using the `wc` Command in Linux/Unix**
`wc` (word count) is a utility that counts lines, words, and bytes or characters in files. Its useful for quickly getting file size details in text terms.
---
## ⚙️ Syntax
```bash
wc [option] file
```
---
## 🔎 Basic Usage
```bash
wc file
```
**Example output:**
```
5 6 43 file1
```
This output means:
| Number | Meaning |
| ------ | ------------------- |
| `5` | Number of **lines** |
| `6` | Number of **words** |
| `43` | Number of **bytes** |
---
## 📋 Common Options
| Option | Description | Example |
| ------ | ------------------------- | ------------ |
| `-l` | Count **lines** only | `wc -l file` |
| `-w` | Count **words** only | `wc -w file` |
| `-c` | Count **bytes** only | `wc -c file` |
| `-m` | Count **characters** only | `wc -m file` |
---
## 📌 Notes
* `bytes (-c)` counts raw bytes, which might differ from characters (`-m`) in multibyte encodings like UTF-8.
* Without options, `wc` outputs lines, words, and bytes by default.

View File

@@ -0,0 +1,79 @@
# ⚙️ PS Command
The `ps` (process status) command is used to **view running processes** on a Linux system. Its useful for monitoring and troubleshooting tasks.
---
## 🧾 Basic Usage
### 🔍 Show tasks in the current shell
```bash
ps
```
### 🔍 Show tasks in the current shell with **full info**
```bash
ps -f
```
---
## 🌍 View System-Wide Processes
### 📋 Show **all** processes
```bash
ps -A
# or
ps -e
```
---
### 👤 Show tasks by **specific user**
```bash
ps -u <username>
```
📌 Replace `<username>` with the actual user name.
---
### 📊 Show **detailed info for all** tasks
```bash
ps aux
```
---
## 📘 Output Fields Explained
| Column | Description |
| --------- | -------------------------------------------------- |
| `USER` | Owner of the process (often `root` or your user) |
| `PID` | Process ID |
| `%CPU` | CPU usage percentage |
| `%MEM` | Memory usage percentage |
| `STAT` | Process state: `R` (running), `S` (sleeping), etc. |
| `START` | Time when the process started |
| `TIME` | Total CPU time used |
| `COMMAND` | Command that started the process |
### 📑 Show List Jobs
```bash
jobs
```
### 🔄Move Process From Background To Forground
```bash
fg
```

View File

@@ -0,0 +1,74 @@
# 🗡️ Kill Command
The `kill` command is used to **send signals to processes**, typically to terminate or control them.
```bash
kill [options] <PID>
```
📌 Replace `<PID>` with the Process ID of the target process.
---
## 🚦 Common `kill` Usage Examples
### 💤 Graceful Termination — `SIGTERM` (Signal 15)
```bash
kill 123
```
✅ Politely asks the process to terminate.
*Allows the process to clean up before exiting.*
---
### 🪓 Force Kill — `SIGKILL` (Signal 9)
```bash
kill -9 123
```
💥 **Immediate termination**.
*Doesnt allow cleanup — use only when necessary.*
🗡️ *Think of it as the "katana" of kill commands.*
### 📑 Multi Process Kill
```bash
pidof <ps-name> | xargs kill -9
```
---
### ⌨️ Interrupt — `SIGINT` (Signal 2)
```bash
kill -2 123
```
🛑 Mimics pressing `Ctrl + C`.
*Often used to stop processes gracefully from the terminal.*
---
### 🔄 Hangup — `SIGHUP` (Signal 1)
```bash
kill -1 123
```
♻️ Requests the process to **reload or restart**.
*Commonly used for daemons or services to reload configs.*
---
## 📋 Summary of Signals
| Signal | Name | Description |
| ------ | --------- | ------------------------------ |
| `1` | `SIGHUP` | Reload configuration / restart |
| `2` | `SIGINT` | Interrupt (like Ctrl + C) |
| `9` | `SIGKILL` | Force kill (cannot be ignored) |
| `15` | `SIGTERM` | Graceful termination (default) |

View File

@@ -0,0 +1,111 @@
# 🧑‍💻 Linux User & Group Management Cheat Sheet
---
## 🔍 Viewing User Info from `/etc/shadow`
```bash
cat /etc/shadow
```
Example entry:
```bash
radin:$y$j9T$gxn.Bgl/nVnzPEeWn0Hrz.$CEeQGtg1TlZ/jwu9Zsz2kkIq3dBtbhJ/bzhVT7cJ1.9:20270:0:99999:7:::
```
| Field | Description | Example |
| ----------------- | -------------------------------------------- | ----------------------------------------------- |
| 👤 Username | Users login name | `radin` |
| 🔒 Password Hash | Encrypted password | `$y$j9T$gxn.Bgl/nVnzPEeWn0Hrz.$CEeQGtg1TlZ/...` |
| 🗓️ Last Changed | Days since Jan 1, 1970 when password changed | `20270` (which is 20270 + 1970 = year) |
| ⏳ Min Age | Minimum days between password changes | `0` |
| ⏰ Max Age | Maximum days before password must be changed | `99999` |
| ⚠️ Warning Period | Days before expiration user is warned | `7` |
---
## 🛡️ Viewing Groups from `/etc/group`
```bash
cat /etc/group
```
Example:
```bash
radin:x:1000:
sudo:x:27:radin
```
| Field | Description | Example |
| ------------- | ------------------------------------ | --------------- |
| 👥 Group Name | Name of the group | `radin`, `sudo` |
| 🔑 Password | Password (usually `x` means none) | `x` |
| 🆔 GID | Group ID | `1000`, `27` |
| 👤 Users | Users in the group (comma-separated) | `radin` |
---
## 👥 Check Groups for a User
```bash
groups <username>
```
---
## 🆔 View User and Group IDs
```bash
id <username>
```
Example output:
```bash
uid=1000(radin) gid=1000(radin) groups=1000(radin),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),100(users),114(lpadmin)
```
---
## Adding Users
| Command | Description |
| -------------------------------------- | ----------------------------------------- |
| `useradd <username>` | Add user without home directory |
| `useradd -m <username>` | Add user **with** home directory |
| `useradd -s /bin/bash -m <username>` | Add user with bash shell & home directory |
| `useradd -G group1,root -m <username>` | Add user with home and extra groups |
---
## 🔑 Changing Password
```bash
passwd <username>
```
---
## ❌ Deleting Users
| Command | Description |
| ----------------------- | ------------------------------------ |
| `userdel <username>` | Delete user |
| `userdel -r <username>` | Delete user and their home directory |
| `userdel -f <username>` | Force delete user |
---
## 🔧 Modifying Users (`usermod`)
| Command | Description |
| ---------------------------------------- | ----------------------------------------- |
| `usermod [options] username` | Modify user with various options |
| `usermod -l <newusername> <oldusername>` | Rename user |
| `usermod -d <dir> -m <username>` | Change user home directory and move files |
| `usermod -G <groups> <username>` | Set new groups (replaces old groups) |
| `usermod -aG <group> <username>` | Add user to a supplementary group |
| `usermod -s <shell> <username>` | Change user login shell |

View File

@@ -0,0 +1,150 @@
# 📁 Linux File Permissions: A Quick & Clear Guide
---
## 🔍 Example: Output of `ls -lh`
Run this command in your terminal:
```bash
ls -lh
```
Example output:
```bash
drwxr-xr-x 3 root root 4.0K Jul 1 22:22 dir1
-rw-r--r-- 1 root root 2.0G Jul 1 21:59 test2.tar
```
---
## 🧠 Understanding the Output Columns
| Column | Description |
| -------------------- | --------------------------------------- |
| `d` / `-` | File type (`d` = directory, `-` = file) |
| `rwxr-xr-x` | Permissions (user, group, others) |
| `3` | Number of hard links |
| `root` | Owner (user) |
| `root` | Group |
| `4.0K` / `2.0G` | File size |
| `Jul 1 22:22` | Last modification date |
| `dir1` / `test2.tar` | File or directory name |
---
## 🔤 First Character: File Type Indicator
* `d` → Directory 📂
* `-` → Regular file 📄
---
## 🔠 File Permissions Breakdown
```
drwxr-xr-x
│││ │ │ │
│││ │ │ └─ Permissions for Others (o)
│││ │ └── Permissions for Group (g)
│││ └──── Permissions for User (u)
│└──────── File type (d = directory, - = file)
└───────── Read (r), Write (w), Execute (x)
```
---
## 🔐 Permission Symbols Explained
| Symbol | Meaning |
| ------ | ------- |
| `r` | Read |
| `w` | Write |
| `x` | Execute |
---
## 👥 Permission Entities
| Symbol | Meaning |
| ------ | ------------ |
| `u` | User (owner) |
| `g` | Group |
| `o` | Others |
| `a` | All |
---
## 🔢 Numeric Permission Values (Octal)
| Value | Binary | Permissions | Meaning |
| ----- | ------ | ----------- | ---------------------- |
| 0 | 000 | --- | No permissions |
| 1 | 001 | --x | Execute only |
| 2 | 010 | -w- | Write only |
| 3 | 011 | -wx | Write + Execute |
| 4 | 100 | r-- | Read only |
| 5 | 101 | r-x | Read + Execute |
| 6 | 110 | rw- | Read + Write |
| 7 | 111 | rwx | Read + Write + Execute |
---
## 🛠️ Changing Permissions with `chmod`
### Syntax:
```bash
chmod [permissions] [filename]
```
### Example (numeric):
```bash
chmod 755 myscript.sh
```
### What does `755` mean?
| Entity | Value | Permission |
| ------ | ----- | -------------------------- |
| User | 7 | rwx (read, write, execute) |
| Group | 5 | r-x (read, execute) |
| Others | 5 | r-x (read, execute) |
### Recursive permission change:
```bash
chmod -R <permission> <directory>
```
---
## 👑 Changing Ownership with `chown`
### Syntax:
```bash
chown [options] owner[:group] file
```
### Examples:
Change owner only:
```bash
sudo chown radin file.txt
```
Change owner and group:
```bash
sudo chown radin:dev file.txt
```
Change owner and group recursively (for directories):
```bash
sudo chown -R radin:dev files/
```

View File

@@ -0,0 +1,148 @@
# 🌐 IP Command Cheat Sheet
The `ip` command is a powerful tool for network configuration and management in Linux. It replaces many of the older `ifconfig` functionalities.
---
## 📌 General Syntax
```bash
ip [ OPTIONS ] OBJECT { COMMAND | help }
```
**Common OBJECTS:**
* `addr` IP addresses
* `link` Network interfaces
* `route` Routing tables
* `neigh` ARP table
* `rule`, `netns`, etc.
---
## 🔍 View Network Information
### Show All IP Addresses
```bash
ip addr show
# or shorthand:
ip a
```
### Show IP for Specific Interface
```bash
ip addr show dev eth0
```
### Show Link Layer Information
```bash
ip link show
```
---
## 🔧 Interface Management
### Bring Interface Down
```bash
ip link set eth0 down
```
### Bring Interface Up
```bash
ip link set eth0 up
```
---
## 🌐 IP Address Configuration
### Add an IP Address
```bash
ip addr add 192.168.1.10/24 dev eth0
```
### Delete an IP Address
```bash
ip addr del 192.168.1.10/24 dev eth0
```
---
## 🛣️ Routing
### Show Routing Table
```bash
ip route show
```
### Add a Default Gateway
```bash
ip route add default via 192.168.1.1
```
### Add a Specific Route
```bash
ip route add 192.168.10.0/24 via 192.168.5.2
```
### Delete a Specific Route
```bash
ip route del 192.168.10.0/24 via 192.168.5.2
```
---
## 🧱 Bridge Interface Management
### Create a Bridge
```bash
ip link add name br0 type bridge
```
### Delete a Bridge
```bash
ip link delete br0
```
### Bring Bridge Up
```bash
ip link set br0 up
```
---
## 🛠️ Example: Set a Static IP Address
```bash
ip link set ens33 up
ip addr add 10.10.40.12/24 dev ens33
ip route add default via 10.10.40.1
```
---
### ✅ Tip:
Always verify with:
```bash
ip a
ip r
```

View File

@@ -0,0 +1,74 @@
# 🛣️ `route` Command Documentation
The `route` command is used to view and manipulate the IP routing table in Linux systems. Below is a concise guide to listing, adding, and deleting routes using `route`.
---
## 📋 View Routing Table
```bash
route -n
```
* **Description**: Displays the kernel routing table.
* **`-n`**: Shows numerical addresses instead of resolving hostnames (faster and cleaner).
---
## Add Routes
### Add a Network Route
```bash
route add -net 10.10.10.0 netmask 255.255.255.0 gw 192.168.1.1
```
* **`-net 10.10.10.0`**: Specifies the network address.
* **`netmask 255.255.255.0`**: Defines the subnet mask for the network.
* **`gw 192.168.1.1`**: Sets the gateway through which packets will be routed.
### Add a Default Gateway
```bash
route add default gw 192.168.1.1
```
* **default**: Indicates this is the default route.
* **`gw 192.168.1.1`**: The default gateway IP address for all traffic not destined for a known network.
---
## ❌ Delete Routes
### Delete a Network Route
```bash
route del -net 10.10.10.0 netmask 255.255.255.0
```
* Removes the specified network route.
### Delete the Default Route
```bash
route del default
```
* Removes the current default gateway.
---
## 📎 Notes
* These commands typically require **superuser (root)** privileges. Use `sudo` if needed:
```bash
sudo route add ...
```
* Consider using `ip route` instead of `route`, as `route` is deprecated on some modern distributions:
```bash
ip route show
```

View File

@@ -0,0 +1,102 @@
# 🌐 `netstat` and `ss` Command Documentation
This guide provides essential usage examples for the `netstat` and `ss` commands to monitor network connections, listening ports, and socket statistics in Linux.
---
## 📡 `netstat` Network Statistics
`netstat` is a legacy tool used for displaying network connections, routing tables, interface statistics, masquerade connections, and multicast memberships.
> ⚠️ `netstat` may be deprecated on some systems. Consider using `ss` as a modern replacement.
### 🔍 Show All Active Network Connections
```bash
netstat
```
* Displays all active sockets (both listening and non-listening).
* Includes TCP, UDP, UNIX domain sockets, etc.
---
### 🎧 Show Listening Ports
```bash
netstat -l
```
* Lists all **listening** ports (TCP and UDP).
* Useful for checking which services are waiting for incoming connections.
---
### 🔒 Show Listening TCP Ports
```bash
netstat -lt
```
* Lists only **TCP** ports in the **listening** state.
---
### 📡 Show Listening UDP Ports
```bash
netstat -lu
```
* Lists only **UDP** ports in the **listening** state.
---
### 🧠 Show Listening TCP/UDP Ports with Process Info
```bash
netstat -tulpn
```
* Shows all listening **TCP/UDP** ports.
* Includes **process ID (PID)** and **program name**.
* Useful for identifying which service is using a specific port.
---
## ⚡ `ss` Socket Statistics (Modern Alternative)
`ss` is a faster and more powerful alternative to `netstat` for displaying socket statistics.
### Common `ss` Options
| Option | Description |
| ------ | -------------------------------------------- |
| `-t` | Show TCP sockets |
| `-u` | Show UDP sockets |
| `-l` | Show only listening sockets |
| `-n` | Show numerical addresses (no DNS resolution) |
| `-p` | Show process using the socket |
| `-a` | Show all sockets |
### Example Show Listening TCP/UDP with Process Info
```bash
ss -tulpn
```
* Equivalent to `netstat -tulpn`
* Recommended for modern Linux distributions.
---
## ✅ Summary
| Task | `netstat` Command | `ss` Equivalent |
| ----------------------------------- | ----------------- | --------------- |
| Show all connections | `netstat` | `ss -a` |
| Show listening ports | `netstat -l` | `ss -l` |
| Show listening TCP ports | `netstat -lt` | `ss -lt` |
| Show listening UDP ports | `netstat -lu` | `ss -lu` |
| Show listening TCP/UDP with process | `netstat -tulpn` | `ss -tulpn` |

View File

@@ -0,0 +1,66 @@
# 🔗 **Linux Links: Soft Link vs Hard Link**
## 📝 **Types of Links**
In Linux, there are **two types** of links:
1. 🪶 **Soft Link** (Symbolic Link)
2. 🪨 **Hard Link**
---
## ⚙️ **Commands**
### 🪶 **Soft Link (Symbolic Link)**
Acts like a **shortcut** pointing to the original file.
```bash
ln -s <base-file> <link-file>
```
💡 **Example:**
```bash
ln -s file.txt file_link.txt
```
---
### 🪨 **Hard Link**
Points directly to the file's **inode** (physical data on disk).
```bash
ln <base-file> <link-file>
```
💡 **Example:**
```bash
ln file.txt file_hard.txt
```
---
## 📊 **Soft Link vs Hard Link**
| 🏷️ Feature | 🪶 Soft Link (Symbolic) | 🪨 Hard Link |
| ------------------------- | --------------------------------- | ----------------------------- |
| 🔢 **Inode Number** | Different from the original file | Same as original file |
| 🗂 **Cross Filesystem** | ✅ Yes | ❌ No |
| ❌ **If Original Deleted** | Link breaks (becomes invalid) | File still exists |
| 📦 **Storage** | Stores path to original file | Stores actual data reference |
| 🔄 **Update** | Reflects changes in original file | Reflects changes (same inode) |
---
## 🧠 **Quick Notes**
* **Soft Link** → Think *shortcut* 📎
* **Hard Link** → Think *clone reference* 📀
* If you delete the **base file**:
* 🪶 Soft Link → ❌ Broken link
* 🪨 Hard Link → ✅ Still works (data intact)

View File

@@ -0,0 +1,67 @@
# 💽 **Disk Partition Types & Commands Guide**
## 🗂 **Partition Types**
### 1⃣ **MBR (Master Boot Record)**
* 📏 **Max Disk Size:** 2 TB
* 📦 **Partition Entries:** 4
---
### 2⃣ **GPT (GUID Partition Table)**
* 📏 **Max Disk Size:** 9 ZB (zettabytes)
* 📦 **Partition Entries:** 128
---
## 📊 **Disk Space & Usage Commands**
### 🖥 **`df` Show Disk Space Usage**
The `df` command displays information about available and used disk space.
| Command | Description |
| --------------------- | ---------------------------------------- |
| `df` | 📄 Show disk space in default format |
| `df -h` | 🧍 Human-readable sizes (e.g., GB, MB) |
| `df -T` | 📂 Show file system type |
| `df -i` | 🔢 Show inode usage |
| `df -h /home` | 🏠 Show usage for `/home` directory only |
---
### 📦 **`du` Show Disk Usage**
The `du` command shows how much space files and directories take up.
| Command | Description |
| ----------------------------- | ---------------------------------------- |
| `du` | 📄 Show disk usage in blocks |
| `du -h` | 🧍 Human-readable sizes |
| `du -sh` | 📊 Summary of current directory |
| `du -h --max-depth=1` | 📂 Usage per subdirectory (1 level deep) |
---
## 🔍 **Disk & Partition Information Commands**
### 💿 **`lsblk`**
Shows partitions, disks, sizes, and mount points.
```bash
lsblk
```
---
### 🆔 **`blkid`**
Displays partition UUIDs and types.
```bash
blkid
```

View File

@@ -0,0 +1,110 @@
# 📘 Disk Partitioning Guide: MBR & GPT using `fdisk` and `gdisk`
## 🔹 Overview
* Use `**fdisk**` for **MBR (Master Boot Record)** partitioning.
* For **GPT (GUID Partition Table)**, the recommended tool is `**gdisk**`, but `fdisk` also supports GPT.
---
## 🧰 Disk Partitioning with `fdisk`
### 🔍 List Partitions
| Command | Description |
| ---------- | ----------------------------------- |
| `fdisk -l` | Show list of available partitions |
| `fdisk -x` | Show list with extended information |
### ⚙️ Launch `fdisk`
```bash
fdisk /dev/sdX
```
Replace `/dev/sdX` with your actual disk name (e.g., `/dev/sdb`).
---
### 📖 Inside `fdisk`
Once inside the `fdisk` prompt:
| Key | Function |
| --- | --------------------------------- |
| `m` | Show help |
| `p` | Print partition table (disk info) |
| `n` | Create new partition |
| `t` | Change partition type |
| `w` | Write changes and exit |
#### Creating a Partition (`n`)
* Choose **`p`** for **primary** or **`e`** for **extended** partition.
* MBR allows **4 primary** partitions. One of them can be **extended**, which can hold **logical** partitions.
#### 📏 Define Partition Size
Example:
```bash
+512M
```
---
## 🧱 Create Filesystem
To format the partition with `ext4`:
```bash
mkfs.ext4 /dev/sdb1
```
---
## 🔗 Get Partition UUID
Option 1: After formatting, the UUID is shown in output.
Option 2: Use `blkid` to retrieve it:
```bash
blkid
```
---
## 📝 Mount Using `/etc/fstab`
1. Open the `fstab` configuration file:
```bash
vim /etc/fstab
```
2. Add the following line:
```
/dev/disk/by-uuid/<UUID> <mount_path> <filesystem> defaults 0 1
```
### Example:
```
/dev/disk/by-uuid/1eb043d2-f2ee-4a69-a7c4-13c283c3ccc6 /test ext4 defaults 0 1
```
This ensures the partition is mounted automatically at boot.
---
## ✅ Summary
| Task | Command/Action |
| ------------------ | --------------------- |
| List partitions | `fdisk -l` |
| Start partitioning | `fdisk /dev/sdX` |
| Format partition | `mkfs.ext4 /dev/sdX1` |
| Get UUID | `blkid` |
| Edit fstab | `vim /etc/fstab` |

View File

@@ -0,0 +1,29 @@
## 🖥️ Viewing Memory Usage with `free`
The `free` command shows your systems memory usage.
```bash
free
```
For **human-readable** output (MB, GB, etc.):
```bash
free -h
```
**📊 Explanation of columns:**
| Column | Description |
| ---------------- | ------------------------------------------------------------------ |
| **💾 total** | Total physical memory (RAM) available in the system. |
| **📂 used** | Memory currently used by processes and the system. |
| **🆓 free** | Completely unused RAM (not allocated to anything). |
| **🔄 shared** | Memory shared between multiple processes. |
| **⚡ buff/cache** | Memory used for file buffers and cache to improve performance. |
| **✅ available** | Estimated memory available for starting new apps without swapping. |
💡 **Pro Tip:**
* `✅ available` is more useful than `🆓 free` for knowing how much memory you can actually use, since Linux keeps unused memory in cache for speed.

View File

@@ -0,0 +1,34 @@
## 🕵️‍♂️ Monitoring Processes with `top`
The `top` command provides a simple, real-time overview of all running processes and system stats.
```bash
top
```
### Sample output header:
```bash
top - 21:28:31 up 10:05, 5 users, load average: 0.19, 0.26, 0.23
Tasks: 382 total, 1 running, 381 sleeping, 0 stopped, 0 zombie
%Cpu(s): 8.0 us, 1.8 sy, 0.0 ni, 90.2 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
MiB Mem : 19754.0 total, 14439.8 free, 3207.1 used, 2871.8 buff/cache
MiB Swap: 8192.0 total, 8192.0 free, 0.0 used. 16547.0 avail Mem
```
### What each part means:
| Item | Description |
| ----------------- | ------------------------------------------------------------------------------- |
| 🕒 `21:28:31` | Current system time |
| ⏳ `up 10:05` | System uptime — 10 hours and 5 minutes since last boot |
| 👥 `5 users` | Number of users currently logged in |
| 📈 `load average` | CPU load averages over 1, 5, and 15 minutes (fractions of total CPU cores used) |
| | — 0.19 = load in last 1 min |
| | — 0.26 = load in last 5 min |
| | — 0.23 = load in last 15 min |

View File

@@ -0,0 +1,47 @@
## 📊 Network Monitoring with `nload`
```bash
nload [options] [interface]
```
* If no interface is specified, `nload` lists available interfaces and lets you choose one.
* Displays **two graphs**:
🔽 Incoming traffic
🔼 Outgoing traffic
---
### ⚙️ Options
| Option | Description |
| ------------------- | ----------------------------------------------------------------------------------------------------- |
| `-u <unit>` | Set unit for data rates (bits, bytes, kilobits, etc.) Options: `b`, `B`, `k`, `m`, `g` (default: `b`) |
| `-t <milliseconds>` | Refresh interval in milliseconds (default: 500 ms) |
| `-m` | Show minimum and maximum network usage statistics |
| `-a` | Show average network usage statistics |
| `-q` | Quiet mode — no graphical output, only numeric data |
| `-V` | Show version info and exit |
| `-h` | Show help message and exit |
---
### 💡 Examples
**Monitor a specific interface (e.g., eth0):**
```bash
nload eth0
```
**Use bytes per second as unit:**
```bash
nload -u B eth0
```
**Set refresh interval to 1 second:**
```bash
nload -t 1000 eth0
```

View File

@@ -0,0 +1,313 @@
# `find` — quick reference & practical documentation
This is a compact, practical reference for the Unix/Linux `find` command aimed at DevOps engineers and system administrators. It covers common options, tests, actions, operators, examples (safe and practical) and performance tips.
---
# Synopsis
```
find [path...] [expression]
```
If no `path` is given, `find` searches the current directory (`.`). `expression` is evaluated left-to-right and can contain tests, actions and operators.
---
# Basic behaviour
* `find` walks directory trees recursively by default.
* An *expression* evaluates to true/false; when true, the default action `-print` (or whatever action is specified) is executed.
* You can control traversal order with `-depth` and `-maxdepth`/`-mindepth`.
* `-prune` prevents descending into directories.
---
# Common options and switches
* `-H` : follow symbolic links specified on the command line.
* `-L` : follow all symbolic links.
* `-P` : never follow symbolic links (default).
* `-xdev` : don't descend into directories on other filesystems (useful when walking `/`).
* `-mindepth N` : do not apply tests/actions to files at depth < N.
* `-maxdepth N` : do not descend past depth N.
* `-depth` : process directory contents before the directory itself (useful for safe deletes).
* `-mount` : same as `-xdev` (GNU find).
---
# Common tests (predicates)
* `-name pattern` : match basename with shell globbing (case-sensitive). Pattern uses shell wildcards (`*`, `?`, `[]`).
* `-iname pattern` : case-insensitive `-name`.
* `-path pattern` : match the whole path (slash-separated) with shell globbing.
* `-ipath pattern` : case-insensitive `-path`.
* `-regex pattern` : match full path with regular expression (syntax differs by `find` implementation; GNU `find` defaults to Emacs regex).
* `-type c` : file type; `f` = regular file, `d` = directory, `l` = symlink, `c` = character device, `b` = block device, `p` = FIFO, `s` = socket.
* `-perm mode` : file permission test. Modes:
* octal: `-perm 0644` (exact)
* symbolic: `-perm -u=w` (any of the bits), `-perm /u=w` (any), `-perm -0644` (all bits set)
* GNU `find` also accepts `/mode` to mean "any of the bits".
* `-user name` / `-uid uid` : owner.
* `-group name` / `-gid gid` : group.
* `-size n[cwbk]` : file size; default 512-byte blocks for some `find` versions; most use 1K blocks for `k`. GNU `find` suffixes:
* `c` = bytes
* `k` = kilobytes
* `M` = megabytes
* `G` = gigabytes
* `+n` = greater than n, `-n` = less than n, `n` = exactly n
* `-mtime n` / `-atime n` / `-ctime n` : modified / accessed / changed time in 24-hour periods; `-mtime +7` older than 7 days, `-mtime -7` less than 7 days, `-mtime 7` exactly 7.
* `-mmin n`, `-amin n`, `-cmin n` : minutes.
* `-newer file` : newer than file (can be combined with `!` to negate).
* `-empty` : empty file or directory.
* `-links n` : number of hard links.
* `-readable` / `-writable` / `-executable` : access checks from running user perspective.
---
# Common actions
* `-print` : print path (often default; some implementations require explicit `-print` with complex expressions).
* `-print0` : print paths separated by NUL (safe with whitespace/newlines).
* `-ls` : list file using `ls -dils` style.
* `-exec command {} \;` : run `command` once per matched file. `{}` is replaced by the current path. The `\;` terminator must be escaped or quoted.
* `-exec command {} +` : optimized form; appends multiple matches to command arguments like `xargs` (more efficient).
* `-ok command {} \;` : like `-exec` but prompts the user before each execution.
* `-delete` : delete matched files/directories (be careful; obeys ordering and `-depth`).
* `-prune` : exclude directory from descent (returns true; often used with `-o`).
* `-quit` : stop after first match (very efficient when used with `-print`).
* `-mindepth N`, `-maxdepth N` already described; they behave like tests.
---
# Operator precedence (GNU `find` style)
* Parentheses `(` `)` group expressions. They must be escaped or quoted: `\( ... \)` or `'(' ... ')'`.
* `!` or `-not` : logical NOT (unary).
* `-a` or implicit concatenation : logical AND.
* `-o` or `-or` : logical OR.
* Evaluation is left-to-right; `-a` has higher precedence than `-o`. Use parentheses to be explicit.
* Common pitfall: mixing `-prune` and `-o` requires careful grouping:
Example pattern to exclude `dir`:
```
find . -path ./dir -prune -o -print
```
This means: if path is `./dir` prune it (and `-prune` returns true) otherwise (`-o`) `-print`.
---
# Typical practical examples
Search examples assume `bash` shell; escape parentheses and semicolons as needed.
1. Find files by name (case-sensitive)
```
find /var/log -type f -name "syslog*"
```
2. Case-insensitive:
```
find /home -type f -iname "*.jpg"
```
3. Find empty directories:
```
find /path -type d -empty
```
4. Delete `*.tmp` files safely (print first, then delete)
```
find /data -type f -name "*.tmp" -print
find /data -type f -name "*.tmp" -delete
```
Or safer with confirmation:
```
find /data -type f -name "*.tmp" -ok rm {} \;
```
5. Find and remove files older than 30 days (safe: use `-print` first)
```
find /var/log -type f -mtime +30 -print
find /var/log -type f -mtime +30 -exec rm -- {} +
```
Prefer `-exec ... +` over `-exec ... \;` for efficiency.
6. Remove directories older than 30 days (use `-depth` to ensure files inside are removed first)
```
find /tmp -depth -type d -mtime +30 -exec rm -rf -- {} +
```
`-delete` may also be used but beware of ordering; `-depth` ensures children processed before parent.
7. Find files with spaces and handle them safely:
```
find /srv -type f -name "*.conf" -print0 | xargs -0 grep -H "pattern"
```
8. Find files larger than 100 MiB:
```
find / -type f -size +100M -print
```
9. Find files newer than a reference file:
```
find /web -type f -newer /tmp/deploy_marker -print
```
10. Find and run a command on many files (batching):
```
find /data -type f -name "*.log" -exec gzip -- {} +
```
11. Exclude a directory (`dir_to_skip`) while listing everything else:
```
find . -path "./dir_to_skip" -prune -o -print
```
12. Only search one level (non-recursive):
```
find . -maxdepth 1 -type f -print
```
13. Find broken symlinks:
```
find / -xtype l -print
```
Note: `-xtype` tests the target type; `-L` changes behavior of `-type`.
14. Use `-printf` to customize output (GNU find):
```
find . -type f -printf "%p\t%k KB\t%TY-%Tm-%Td %TH:%TM:%TS\n"
```
`-printf` supports format sequences (`%p` path, `%s` bytes, `%k` KB blocks, `%TY` year, ...). Exact spec depends on implementation (GNU has extensive options).
15. Stop at first match (fast):
```
find /usr -type f -name "passwd" -print -quit
```
16. Find files modified within last 15 minutes:
```
find /var -type f -mmin -15
```
---
# Safe deletion checklist
* Always `-print` or `-ls` first to verify matches.
* Prefer `-exec rm -- {} +` or use `-delete` with `-depth` if required.
* Watch out for `-maxdepth`/`-mindepth` to avoid accidental top-level deletions.
* Use `-print0` + `xargs -0` when passing to other utilities.
* Consider using `-ok` for destructive changes in interactive contexts.
---
# Performance & scalability tips
* Limit scope: pass explicit starting paths instead of `.` or `/` when possible.
* Use `-maxdepth` and `-mindepth` to reduce traversal.
* Use `-xdev` to avoid crossing filesystem boundaries (speeds up root scans).
* Combine fast tests early (e.g., `-type f -name "*.log"` rather than `-name` alone) because find evaluates left-to-right; short-circuiting happens when possible.
* Prefer `-exec ... +` to `-exec ... \;` to reduce process spawn overhead.
* Use `-prune` to skip large tree branches that arent needed.
* On very large trees consider tools optimized for indexing (e.g., `locate` / `mlocate`, `fd`, or ripgrep for content search). `find` is always consistent but traverses the disk each run.
---
# Portability notes
* Behavior, available tests/actions and argument formats vary slightly between implementations (GNU `find` vs BSD `find` vs BusyBox). Examples above assume GNU `find` when using `-printf`, `-delete`, `-quit` or suffixes like `M`/`G` for sizes.
* When writing scripts for mixed environments, try to stick to portable tests: `-name`, `-type`, `-mtime`, `-print`, `-exec ... \;`. Check `/usr/bin/find --version` or `man find` on target hosts.
---
# Gotchas & common pitfalls
* Shell globbing vs `find` globbing: `-name "*.txt"` is matched by `find` and must be quoted to prevent shell expansion.
* `-perm` exact vs any-bit semantics differ across versions; test on target system.
* `-regex` matches the whole path, not just basename; regex dialect differs (use `-regextype posix-extended` on GNU `find` to set type).
* `-delete` will fail if used before tests that select children (order matters). Use `-depth` or test ordering appropriately.
* Beware of running `find` as root with `-exec rm -rf {}` — very dangerous if expression is wrong. Always verify output.
* `-maxdepth`/`-mindepth` may not be supported in very old `find` implementations.
---
# Exit status
* `0` : at least one match and command completed successfully.
* `1` : no matches were found (behavior can vary).
* `>1` : an error occurred (e.g., permission errors or malformed expression).
Note: exact meanings can depend on implementation.
---
# Useful combinations
* Find files and preserve relative paths for tar:
```
cd /path && find . -type f -name "*.conf" -print0 | tar --null -T - -czf confs.tar.gz
```
* Find and change ownership or permissions:
```
find /srv/www -type f -name "*.php" -exec chown www-data:www-data {} +
find /srv/www -type d -exec chmod 755 {} +
```
* Search content in matched files:
```
find /app -type f -name "*.py" -print0 | xargs -0 grep -n "TODO"
```
---
# Related commands/tools
* `locate` / `mlocate` : fast filename lookup (uses database).
* `fd` : simpler, faster user-friendly alternative to `find` (not always installed).
* `xargs` : pass batches of arguments to commands (careful with spaces; use `-print0` + `xargs -0`).
* `stat` : detailed file metadata for a single file.
* `rm`, `tar`, `gzip`, `chown`, `chmod`, `rsync` : commonly used alongside `find`.
---
# Quick cheatsheet (most-used patterns)
* Find files by name: `find /path -type f -name "pattern"`
* Case-insensitive: `-iname`
* Size bigger than 100M: `-size +100M`
* Modified > 7 days: `-mtime +7`
* Delete old files: `find /dir -type f -mtime +30 -exec rm -- {} +`
* Print NUL-separated: `-print0`
* Safe prune: `find . -path ./skip -prune -o -print`
* Batch exec: `-exec cmd {} +`
* Stop on first: `-print -quit`

View File

@@ -0,0 +1,190 @@
# diff Command Reference
The `diff` command is a standard Unix/Linux utility used to compare files line by line. It is commonly used in development, DevOps, and system administration to identify changes between configuration files, source code, logs, or generated outputs.
---
## 1. Basic File Comparison
Compare two files line by line:
```bash
diff file1 file2
```
### Output Behavior
* Shows only the lines that differ
* Uses symbols to indicate changes:
* `<` line from `file1`
* `>` line from `file2`
* `c` change
* `a` addition
* `d` deletion
---
## 2. Side-by-Side Comparison
Display files next to each other:
```bash
diff -y file1 file2
```
### Notes
* Useful for human-readable comparison
* Differences are shown in two columns
* Change indicators appear in the middle
Limit output width:
```bash
diff -y --width=120 file1 file2
```
Suppress common lines:
```bash
diff -y --suppress-common-lines file1 file2
```
---
## 3. Unified Diff Format (Most Common)
Generate a unified diff:
```bash
diff -u file1 file2
```
### Why Unified Diff
* Standard format used by Git, patch, and code reviews
* Shows context before and after changes
* Easier to read and apply
Example output markers:
* `+` added lines
* `-` removed lines
* `@@` line numbers and context
---
## 4. Save Diff Output to a File
Redirect diff output to a file:
```bash
diff -u file1 file2 > different.diff
```
Common use cases:
* Code reviews
* Patch creation
* Change tracking
* CI/CD artifact storage
---
## 5. Recursive Directory Comparison
Compare directories:
```bash
diff -r dir1 dir2
```
Unified recursive diff:
```bash
diff -ru dir1 dir2
```
Ignore missing files:
```bash
diff -rq dir1 dir2
```
---
## 6. Ignore Differences
Ignore whitespace:
```bash
diff -w file1 file2
```
Ignore blank lines:
```bash
diff -B file1 file2
```
Ignore case differences:
```bash
diff -i file1 file2
```
---
## 7. Apply a Diff as a Patch
Create a patch:
```bash
diff -u oldfile newfile > change.patch
```
Apply patch:
```bash
patch < change.patch
```
Dry-run patch:
```bash
patch --dry-run < change.patch
```
---
## 8. diff vs Git diff
| diff | git diff |
| -------------------- | ------------------------------- |
| Compares any files | Compares Git-tracked files |
| Works without Git | Requires Git repository |
| Produces patch files | Integrated with version control |
---
## 9. Best Practices
* Use `-u` format for readability and compatibility
* Store diff files with `.diff` or `.patch` extensions
* Avoid committing generated diff files unless required
* Use `diff` for system configuration audits
* Use `git diff` inside Git repositories
---
## 10. Quick Reference
```bash
diff file1 file2
diff -y file1 file2
diff -u file1 file2
diff -ru dir1 dir2
diff -u file1 file2 > change.diff
```

View File

@@ -0,0 +1,243 @@
Here is a cleaned up, expanded, and more production-ready version of your **date and time manipulation** document, written from a DevOps / Linux system administration perspective and keeping it concise and accurate.
---
# Essential Date and Time Manipulation Commands
This document covers common shell commands for working with dates and times. These commands are frequently used in scripting, logging, monitoring, automation, and system administration tasks.
---
## 1. The `date` Command Overview
The `date` command is a standard Unix/Linux utility used to:
* Display the current system date and time
* Format timestamps
* Convert between human-readable dates and Unix epoch time
* Perform date arithmetic
Check system time:
```bash
date
```
---
## 2. Creating Epoch Timestamps
### Current Epoch Time (Seconds)
```bash
date +%s
```
Output example:
```
1737154200
```
### Current Epoch Time (Milliseconds)
```bash
date +%s%3N
```
Notes:
* `%s` → seconds since Unix epoch
* `%3N` → milliseconds (GNU date only)
---
### Convert Specific Date to Epoch (Milliseconds)
Convert a human-readable date to epoch time:
```bash
date -d "2026-01-13 14:31:26" +%s%3N
```
Common use cases:
* Log correlation
* API timestamps
* CI/CD pipeline timing
* Monitoring and alerting
---
## 3. Formatting Current Date and Time
Custom output formats are widely used in scripts and logs.
### Common Date Formats
| Command | Description | Example Output |
| --------------------------- | --------------------- | ---------------------------- |
| `date` | Default system format | Wed Jan 17 10:30:00 UTC 2026 |
| `date +'%Y-%m-%d %H:%M:%S'` | ISO-like format | 2026-01-17 10:30:00 |
| `date +'%Y-%m-%d'` | Date only | 2026-01-17 |
| `date +'%H:%M:%S'` | Time only | 10:30:00 |
| `date +%s` | Epoch (seconds) | 1737154200 |
### Common Format Specifiers
| Specifier | Meaning |
| --------- | --------------- |
| `%Y` | Year (4 digits) |
| `%m` | Month (0112) |
| `%d` | Day (0131) |
| `%H` | Hour (0023) |
| `%M` | Minute (0059) |
| `%S` | Second (0060) |
| `%N` | Nanoseconds |
---
## 4. Converting Epoch to Human-Readable Time
Convert epoch seconds to readable format:
```bash
date -d @1737154200
```
Using a variable:
```bash
EPOCH_TIME=1737154200
date -d @"$EPOCH_TIME"
```
Formatted output:
```bash
date -d @"$EPOCH_TIME" '+%Y-%m-%d %H:%M:%S'
```
---
## 5. Date Arithmetic
GNU `date` supports flexible date calculations.
### Relative Dates
| Command | Description |
| ----------------------- | ----------------------- |
| `date -d "yesterday"` | Previous day |
| `date -d "tomorrow"` | Next day |
| `date -d "2 days ago"` | Two days in the past |
| `date -d "+1 hour"` | One hour from now |
| `date -d "+30 minutes"` | Thirty minutes from now |
| `date -d "+1 week"` | One week from now |
| `date -d "2 weeks ago"` | Two weeks ago |
---
## 6. Date Arithmetic with Formatting
Example: date 7 days from now:
```bash
date -d "+7 days" '+%Y-%m-%d'
```
Example: timestamp 15 minutes ago (epoch):
```bash
date -d "-15 minutes" +%s
```
---
## 7. Working with UTC and Time Zones
Display current UTC time:
```bash
date -u
```
Format UTC time:
```bash
date -u '+%Y-%m-%d %H:%M:%S'
```
Convert date in a specific timezone:
```bash
TZ=UTC date
TZ=America/New_York date
```
---
## 8. Script-Friendly Usage Examples
Add timestamp to a log entry:
```bash
echo "$(date '+%Y-%m-%d %H:%M:%S') Application started"
```
Generate a timestamped filename:
```bash
backup_$(date +%Y%m%d_%H%M%S).tar.gz
```
Measure execution time:
```bash
start=$(date +%s)
# command here
end=$(date +%s)
echo "Duration: $((end - start)) seconds"
```
---
## 9. macOS Compatibility Notes
macOS uses BSD `date`, which differs from GNU `date`.
Example difference:
```bash
# GNU (Linux)
date -d "yesterday"
# BSD (macOS)
date -v -1d
```
Install GNU date on macOS:
```bash
brew install coreutils
gdate -d "yesterday"
```
---
## 10. Best Practices
* Use UTC for logs and distributed systems
* Store timestamps as epoch values when possible
* Format dates only at display time
* Avoid locale-dependent formats in scripts
* Be aware of GNU vs BSD `date` differences
---
If you want, I can:
* Add cron-specific date examples
* Add log rotation and backup use cases
* Provide a quick-reference cheat sheet
* Add cross-platform date handling strategies