removed space from dir names
This commit is contained in:
60
Linux/Bash-Script/01-Echo.md
Normal file
60
Linux/Bash-Script/01-Echo.md
Normal file
@@ -0,0 +1,60 @@
|
||||
### 📌 Echo Basic Usage
|
||||
|
||||
```bash
|
||||
echo Hello, world!
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
Hello, world!
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 💡 Common Use Cases
|
||||
|
||||
1. **Print plain text:**
|
||||
|
||||
```bash
|
||||
echo This is a message
|
||||
```
|
||||
|
||||
2. **Print environment variables (Linux/macOS):**
|
||||
|
||||
```bash
|
||||
echo $HOME
|
||||
```
|
||||
|
||||
3. **Print environment variables (Windows):**
|
||||
|
||||
```cmd
|
||||
echo %USERNAME%
|
||||
```
|
||||
|
||||
4. **Write to a file:**
|
||||
|
||||
```bash
|
||||
echo "Log entry" >> logfile.txt
|
||||
```
|
||||
|
||||
5. **Suppress newline (Unix/Linux):**
|
||||
|
||||
```bash
|
||||
echo -n "No newline"
|
||||
```
|
||||
|
||||
6. **Use with escape characters (Unix/Linux):**
|
||||
|
||||
```bash
|
||||
echo -e "Line1\nLine2"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### ⚠️ Notes
|
||||
|
||||
* On **Unix-like systems**, `echo` is a shell builtin (e.g., in `bash`, `sh`).
|
||||
* On **Windows**, it’s a command in `cmd.exe`.
|
||||
* Behavior may vary slightly between environments. For complex text handling, consider using `printf` instead in Unix/Linux.
|
||||
|
||||
91
Linux/Bash-Script/02-Operators.md
Normal file
91
Linux/Bash-Script/02-Operators.md
Normal file
@@ -0,0 +1,91 @@
|
||||
# 🖥️ Bash Operators
|
||||
|
||||
A quick reference guide to essential bash command operators and their usage.
|
||||
|
||||
---
|
||||
|
||||
## `>` — **Write to File (Overwrite)**
|
||||
|
||||
This operator **creates a new file** or **overwrites** the contents of an existing file.
|
||||
|
||||
```bash
|
||||
echo "Hi" > file1
|
||||
```
|
||||
|
||||
📄 *Creates* `file1` and writes `"Hi"` into it. If `file1` already exists, its content is replaced.
|
||||
|
||||
---
|
||||
|
||||
## `>>` — **Append to File**
|
||||
|
||||
Adds content to the **end of an existing file** without deleting what's already there.
|
||||
|
||||
```bash
|
||||
echo "Hi" >> file1
|
||||
```
|
||||
|
||||
📝 *Appends* `"Hi"` to the end of `file1`.
|
||||
|
||||
---
|
||||
|
||||
## `&&` — **AND Operator**
|
||||
|
||||
Runs the **second command only if the first succeeds**.
|
||||
|
||||
```bash
|
||||
apt update && apt upgrade
|
||||
```
|
||||
|
||||
🔗 `apt upgrade` runs only if `apt update` completes successfully.
|
||||
|
||||
---
|
||||
|
||||
## `;` — **Run Multiple Commands**
|
||||
|
||||
Executes **commands sequentially**, regardless of success or failure.
|
||||
|
||||
```bash
|
||||
echo "Hi" > file1 ; cat file1
|
||||
```
|
||||
|
||||
🔄 Both commands are executed one after the other.
|
||||
|
||||
---
|
||||
|
||||
## `|` — **Pipe Operator**
|
||||
|
||||
Takes the **output of the command on the left** and **uses it as input for the command on the right**.
|
||||
|
||||
```bash
|
||||
ls -l | grep "txt"
|
||||
```
|
||||
|
||||
🔗 Passes the output of `ls -l` to `grep "txt"` to filter and display only files containing "txt".
|
||||
|
||||
---
|
||||
|
||||
## `*` — **Wildcard (All Matching Files)**
|
||||
|
||||
Matches **all files** that meet the pattern.
|
||||
|
||||
```bash
|
||||
cat file*
|
||||
```
|
||||
|
||||
🌐 Displays the contents of all files starting with `file`.
|
||||
|
||||
---
|
||||
|
||||
## `[ ... ]` — **Specific Character Matching**
|
||||
|
||||
Reads files that match specific characters at the position defined in brackets.
|
||||
|
||||
```bash
|
||||
cat file[1,2,3]
|
||||
```
|
||||
|
||||
📚 Reads `file1`, `file2`, and `file3` (if they exist). Equivalent to:
|
||||
|
||||
```bash
|
||||
cat file1 file2 file3
|
||||
```
|
||||
95
Linux/Bash-Script/03-Exit-Codes.md
Normal file
95
Linux/Bash-Script/03-Exit-Codes.md
Normal file
@@ -0,0 +1,95 @@
|
||||
# 🧾 Linux Exit Codes Cheat Sheet
|
||||
|
||||
Every command in Linux returns an **exit status code** upon completion. You can check this code using:
|
||||
|
||||
```bash
|
||||
command
|
||||
echo $?
|
||||
```
|
||||
|
||||
These codes are helpful for debugging scripts or understanding command behavior.
|
||||
|
||||
---
|
||||
|
||||
## ✅ Common Exit Codes & Their Meanings
|
||||
|
||||
| Exit Code | Meaning |
|
||||
| --------- | ----------------------------------------------- |
|
||||
| `0` | ✅ Success |
|
||||
| `1` | ❌ General Error |
|
||||
| `2` | ⚠️ Misuse of Shell Built-in (bad options, etc.) |
|
||||
| `126` | 🚫 Command Found but Cannot Execute |
|
||||
| `127` | ❓ Command Not Found |
|
||||
| `130` | ⌨️ Terminated by `Ctrl+C` |
|
||||
| `137` | 💀 Killed (e.g., `kill -9`) |
|
||||
|
||||
---
|
||||
|
||||
## 🔍 Exit Code Examples
|
||||
|
||||
### `0` — Success
|
||||
|
||||
```bash
|
||||
echo "Hello"
|
||||
echo $? # ➜ 0
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `1` — General Error
|
||||
|
||||
```bash
|
||||
grep "text" non_existing_file.txt
|
||||
echo $? # ➜ 1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `2` — Misuse of Shell Built-in
|
||||
|
||||
```bash
|
||||
ls --wrongoption
|
||||
echo $? # ➜ 2
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `126` — Command Found but Not Executable
|
||||
|
||||
```bash
|
||||
touch myscript.sh
|
||||
chmod -x myscript.sh
|
||||
./myscript.sh
|
||||
echo $? # ➜ 126
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `127` — Command Not Found
|
||||
|
||||
```bash
|
||||
nonexistentcommand
|
||||
echo $? # ➜ 127
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `130` — Script Terminated by `Ctrl+C`
|
||||
|
||||
```bash
|
||||
sleep 10
|
||||
# Press Ctrl+C while it sleeps
|
||||
echo $? # ➜ 130
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `137` — Killed by `kill -9`
|
||||
|
||||
```bash
|
||||
sleep 100 &
|
||||
kill -9 $!
|
||||
wait
|
||||
echo $? # ➜ 137
|
||||
```
|
||||
|
||||
80
Linux/Bash-Script/04-Shebang.md
Normal file
80
Linux/Bash-Script/04-Shebang.md
Normal file
@@ -0,0 +1,80 @@
|
||||
|
||||
# 🌟 Understanding the **Shebang** (`#!`)
|
||||
|
||||
A **shebang** (also known as a **hashbang**) is the character sequence:
|
||||
|
||||
```
|
||||
#!<interpreter_path>
|
||||
```
|
||||
|
||||
It appears **at the very top** of a script file and tells the operating system **which interpreter** should execute the file.
|
||||
|
||||
---
|
||||
|
||||
## 📌 What It Looks Like
|
||||
|
||||
```bash
|
||||
#!/usr/bin/python3
|
||||
print("Hello, world!")
|
||||
```
|
||||
|
||||
### Breakdown:
|
||||
|
||||
* `#!` — This is the **shebang**.
|
||||
* `/usr/bin/python3` — This tells the OS to use **Python 3** to run the script.
|
||||
|
||||
---
|
||||
|
||||
## 🧠 Why It Matters
|
||||
|
||||
When you make a script **executable**:
|
||||
|
||||
```bash
|
||||
chmod +x script.py
|
||||
```
|
||||
|
||||
And run it directly:
|
||||
|
||||
```bash
|
||||
./script.py
|
||||
```
|
||||
|
||||
The OS reads the **shebang line** and uses the specified interpreter to execute the file. This works for any script type, like:
|
||||
|
||||
```bash
|
||||
./script.sh # for a Bash script
|
||||
./script.py # for a Python script
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💡 Common Shebang Examples
|
||||
|
||||
| Language | Shebang |
|
||||
| -------- | --------------------- |
|
||||
| Bash | `#!/bin/bash` |
|
||||
| Python | `#!/usr/bin/python3` |
|
||||
| Node.js | `#!/usr/bin/env node` |
|
||||
| Perl | `#!/usr/bin/perl` |
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Pro Tip: Use `env` for Portability
|
||||
|
||||
Instead of hardcoding the interpreter path, use:
|
||||
|
||||
```bash
|
||||
#!/usr/bin/env python3
|
||||
```
|
||||
|
||||
This makes your script more **portable**, as it locates `python3` using the user's `PATH` environment.
|
||||
|
||||
---
|
||||
|
||||
## ✅ Summary
|
||||
|
||||
* The **shebang** defines the script interpreter.
|
||||
* Place it on **the first line** of your script.
|
||||
* Make the script executable with `chmod +x`.
|
||||
* Use `/usr/bin/env` for better portability across systems.
|
||||
|
||||
77
Linux/Bash-Script/05-Variables.md
Normal file
77
Linux/Bash-Script/05-Variables.md
Normal file
@@ -0,0 +1,77 @@
|
||||
# 🧮 Bash Variables
|
||||
|
||||
In **Bash scripting**, **variables** are used to store values like text or numbers. They allow scripts to be dynamic and reusable.
|
||||
|
||||
---
|
||||
|
||||
## ✍️ Defining Variables
|
||||
|
||||
Variables are created **without spaces** around the `=` sign:
|
||||
|
||||
```bash
|
||||
user="ali"
|
||||
age=21
|
||||
```
|
||||
|
||||
* `user` is assigned the value `"ali"`.
|
||||
* `age` is assigned the value `21`.
|
||||
|
||||
> ✅ Tip: No `let` or `var` is needed like in other programming languages.
|
||||
|
||||
---
|
||||
|
||||
## 📢 Using Variables
|
||||
|
||||
You can **access variables** by prefixing them with `$`:
|
||||
|
||||
```bash
|
||||
user="radin"
|
||||
echo "Welcome, $user"
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
Welcome, radin
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Full Script Example
|
||||
|
||||
Here's a complete Bash script using variables:
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
|
||||
user="mmd"
|
||||
age=25
|
||||
|
||||
echo "$user is $age years old."
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
mmd is 25 years old.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📌 Notes
|
||||
|
||||
* Variable names are **case-sensitive** (`User` and `user` are different).
|
||||
* Avoid spaces around `=` when assigning.
|
||||
* Enclose variable values in quotes if they contain spaces.
|
||||
|
||||
---
|
||||
|
||||
## ✅ Summary
|
||||
|
||||
| Task | Syntax |
|
||||
| --------------- | ---------------------------- |
|
||||
| Define variable | `name="value"` |
|
||||
| Use variable | `$name` |
|
||||
| Print value | `echo "$name"` |
|
||||
| With script | Use `#!/bin/bash` at the top |
|
||||
|
||||
77
Linux/Bash-Script/06-Read.md
Normal file
77
Linux/Bash-Script/06-Read.md
Normal file
@@ -0,0 +1,77 @@
|
||||
# 📝 Bash `read` Command
|
||||
|
||||
The `read` command in **Bash** is used to **take user input** from the terminal. It stores the input into one or more **variables**.
|
||||
|
||||
---
|
||||
|
||||
## 🔤 Basic Syntax
|
||||
|
||||
```bash
|
||||
read [options] variable
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📘 Simple Example
|
||||
|
||||
```bash
|
||||
echo "What is your name?"
|
||||
read name
|
||||
echo "Hello, $name!"
|
||||
```
|
||||
|
||||
* `read name` takes input from the user and stores it in the variable `name`.
|
||||
* The script then greets the user with the stored input.
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Prompt Inline with `-p`
|
||||
|
||||
```bash
|
||||
read -p "What is your name? " name
|
||||
echo "Hello, $name!"
|
||||
```
|
||||
|
||||
* `-p` allows you to show the prompt **on the same line** as the user input.
|
||||
|
||||
---
|
||||
|
||||
## 🔒 Silent Input with `-s` (e.g., Passwords)
|
||||
|
||||
```bash
|
||||
read -sp "Enter your password: " password
|
||||
echo $password >> pass.txt
|
||||
```
|
||||
|
||||
* `-s` hides the user’s input while typing (useful for passwords).
|
||||
* `>> pass.txt` appends the password to a file (⚠️ For demonstration only—**avoid storing passwords in plain text**!).
|
||||
|
||||
---
|
||||
|
||||
## ⏳ Set a Timeout with `-t`
|
||||
|
||||
```bash
|
||||
read -t 5 -p "Enter something in 5 seconds: " data
|
||||
```
|
||||
|
||||
* `-t 5` gives the user **5 seconds** to input something.
|
||||
* If no input is given in time, the script moves on.
|
||||
|
||||
---
|
||||
|
||||
## 🧠 Summary Table
|
||||
|
||||
| Option | Description | Example |
|
||||
| ------ | --------------------- | ---------------------------- |
|
||||
| `-p` | Show prompt inline | `read -p "Name: " name` |
|
||||
| `-s` | Silent (hidden input) | `read -sp "Password: " pass` |
|
||||
| `-t` | Timeout (in seconds) | `read -t 10 var` |
|
||||
|
||||
---
|
||||
|
||||
## ✅ Quick Recap
|
||||
|
||||
* Use `read` to get **interactive input** in your Bash scripts.
|
||||
* Combine options (`-sp`, `-tp`, etc.) for powerful input control.
|
||||
* Avoid exposing sensitive data—use secure handling practices.
|
||||
|
||||
175
Linux/Bash-Script/07-If.md
Normal file
175
Linux/Bash-Script/07-If.md
Normal file
@@ -0,0 +1,175 @@
|
||||
|
||||
# 🐚 Bash `if` Statement Guide
|
||||
|
||||
Conditional statements in Bash allow you to execute code based on specific conditions. Below is a comprehensive guide to `if` statements, their syntax, comparison operators, and examples.
|
||||
|
||||
---
|
||||
|
||||
## 🔹 Basic Syntax
|
||||
|
||||
```bash
|
||||
if [[ condition ]]; then
|
||||
# commands if condition is true
|
||||
fi
|
||||
```
|
||||
|
||||
### With `else`
|
||||
|
||||
```bash
|
||||
if [[ condition ]]; then
|
||||
# true
|
||||
else
|
||||
# false
|
||||
fi
|
||||
```
|
||||
|
||||
### With `elif`
|
||||
|
||||
```bash
|
||||
if [[ condition1 ]]; then
|
||||
# condition1 is true
|
||||
elif [[ condition2 ]]; then
|
||||
# condition2 is true
|
||||
else
|
||||
# none matched
|
||||
fi
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ Operators
|
||||
|
||||
### 🔢 Numeric Comparison
|
||||
|
||||
| Operator | Meaning |
|
||||
| -------- | ---------------- |
|
||||
| `-eq` | Equal to |
|
||||
| `-ne` | Not equal |
|
||||
| `-lt` | Less than |
|
||||
| `-le` | Less or equal |
|
||||
| `-gt` | Greater than |
|
||||
| `-ge` | Greater or equal |
|
||||
|
||||
### 🔤 String Comparison
|
||||
|
||||
| Operator | Meaning |
|
||||
| -------- | ---------------- |
|
||||
| `==` | Equal to |
|
||||
| `!=` | Not equal |
|
||||
| `-z` | Empty string |
|
||||
| `-n` | Not empty string |
|
||||
|
||||
### 📁 File Tests
|
||||
|
||||
| Operator | Meaning |
|
||||
| -------- | ------------------ |
|
||||
| `-e` | File exists |
|
||||
| `-d` | Directory exists |
|
||||
| `-r` | File is readable |
|
||||
| `-w` | File is writable |
|
||||
| `-x` | File is executable |
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Practical Examples
|
||||
|
||||
### Example 1: Number Check
|
||||
|
||||
```bash
|
||||
read -p "Enter Your Number: " number
|
||||
|
||||
if [[ $number -eq 0 ]]; then
|
||||
echo "Zero"
|
||||
elif [[ $number -ge 1 ]]; then
|
||||
echo "Positive"
|
||||
else
|
||||
echo "Negative"
|
||||
fi
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Example 2: Number Range with Error Handling
|
||||
|
||||
```bash
|
||||
read -p "Enter Your Number: " number
|
||||
|
||||
if [[ $number -eq 0 ]]; then
|
||||
echo "Zero"
|
||||
elif [[ $number -ge 1 ]]; then
|
||||
echo "Positive"
|
||||
elif [[ $number -le -1 ]]; then
|
||||
echo "Negative"
|
||||
else
|
||||
echo "Error: Invalid input"
|
||||
exit 1
|
||||
fi
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Example 3: String Check
|
||||
|
||||
```bash
|
||||
read -p "Enter Your String: " str
|
||||
|
||||
if [[ -n $str ]]; then
|
||||
if [[ $str == "hello" ]]; then
|
||||
echo "Hi"
|
||||
elif [[ $str != "hello" ]]; then
|
||||
echo "Ok"
|
||||
fi
|
||||
else
|
||||
echo "Nothing to read"
|
||||
exit 1
|
||||
fi
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Example 4: File Existence
|
||||
|
||||
```bash
|
||||
file="script.sh"
|
||||
|
||||
if [[ -e $file ]]; then
|
||||
echo "File exists"
|
||||
else
|
||||
touch "$file"
|
||||
echo "File created"
|
||||
fi
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Example 5: File Permission Check
|
||||
|
||||
```bash
|
||||
file="script50.sh"
|
||||
|
||||
if [[ -e $file ]]; then
|
||||
echo "File exists"
|
||||
|
||||
if [[ ! -x $file ]]; then
|
||||
chmod +x "$file"
|
||||
echo "Executable permission added"
|
||||
fi
|
||||
|
||||
if [[ ! -r $file ]]; then
|
||||
chmod +r "$file"
|
||||
echo "Read permission added"
|
||||
fi
|
||||
else
|
||||
touch "$file"
|
||||
echo "File created"
|
||||
fi
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ Tips
|
||||
|
||||
* Always quote variables: `"$var"` to prevent word splitting.
|
||||
* Use `[[ ... ]]` for conditional tests (preferred over `[ ... ]`).
|
||||
* Prefer `read -r` to avoid backslash escapes.
|
||||
|
||||
90
Linux/Bash-Script/08-Function.md
Normal file
90
Linux/Bash-Script/08-Function.md
Normal file
@@ -0,0 +1,90 @@
|
||||
# 🐚 Bash Function Syntax & Examples
|
||||
|
||||
Bash functions allow you to group reusable logic in shell scripts. Below are clear examples and explanations to help you understand how to define and use them effectively.
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Defining a Function
|
||||
|
||||
You can define a Bash function in two main ways:
|
||||
|
||||
### Option 1: Classic Syntax
|
||||
|
||||
```bash
|
||||
function_name () {
|
||||
# commands
|
||||
}
|
||||
```
|
||||
|
||||
### Option 2: With the `function` Keyword
|
||||
|
||||
```bash
|
||||
function function_name () {
|
||||
# commands
|
||||
}
|
||||
```
|
||||
|
||||
> 💡 Both syntaxes are valid. The use of the `function` keyword is optional and mostly stylistic.
|
||||
|
||||
---
|
||||
|
||||
## 📥 Passing Arguments
|
||||
|
||||
Bash functions accept arguments just like scripts. These are accessed via `$1`, `$2`, etc.
|
||||
|
||||
### Example: Single Argument
|
||||
|
||||
```bash
|
||||
func1() {
|
||||
echo "Arg: $1"
|
||||
}
|
||||
|
||||
func1 "Test"
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
Arg: Test
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ➕ Multiple Arguments & Calculation
|
||||
|
||||
You can perform operations using passed arguments, like arithmetic:
|
||||
|
||||
```bash
|
||||
summery() {
|
||||
local sum=$(( $1 + $2 ))
|
||||
echo $sum
|
||||
}
|
||||
|
||||
summery 5 7
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
12
|
||||
```
|
||||
|
||||
> 📌 `local` ensures `sum` is scoped within the function.
|
||||
|
||||
---
|
||||
|
||||
## ✅ Best Practices
|
||||
|
||||
* Use `local` to avoid polluting the global scope.
|
||||
* Quote variables when dealing with strings.
|
||||
* Use descriptive names for clarity.
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Try It Yourself
|
||||
|
||||
Add these examples to a `.sh` file and run it with:
|
||||
|
||||
```bash
|
||||
bash script.sh
|
||||
```
|
||||
126
Linux/Bash-Script/09-For.md
Normal file
126
Linux/Bash-Script/09-For.md
Normal file
@@ -0,0 +1,126 @@
|
||||
# Bash `for` Loop Cheat Sheet
|
||||
|
||||
A clear and concise reference for using `for` loops in Bash, with syntax variations, examples, and best practices.
|
||||
|
||||
---
|
||||
|
||||
## 1. Basic `for` Loop (List Iteration)
|
||||
|
||||
Iterates over a fixed list of items.
|
||||
|
||||
**Syntax:**
|
||||
|
||||
```bash
|
||||
for VARIABLE in ITEM1 ITEM2 ITEM3 ...
|
||||
do
|
||||
commands
|
||||
DONE
|
||||
done
|
||||
```
|
||||
|
||||
**Example:**
|
||||
|
||||
```bash
|
||||
for color in red green blue
|
||||
do
|
||||
echo "Color: $color"
|
||||
done
|
||||
```
|
||||
|
||||
*Output:*
|
||||
|
||||
```
|
||||
Color: red
|
||||
Color: green
|
||||
Color: blue
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Numeric Iteration Using a List
|
||||
|
||||
When you explicitly list out numbers.
|
||||
|
||||
**Example:**
|
||||
|
||||
```bash
|
||||
for i in 1 2 3 4 5
|
||||
do
|
||||
echo "Number: $i"
|
||||
done
|
||||
```
|
||||
|
||||
*Output:*
|
||||
|
||||
```
|
||||
Number: 1
|
||||
Number: 2
|
||||
Number: 3
|
||||
Number: 4
|
||||
Number: 5
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. C-style `for` Loop (Arithmetic)
|
||||
|
||||
Similar to loops in C-style languages: initialize, condition, increment.
|
||||
|
||||
**Syntax:**
|
||||
|
||||
```bash
|
||||
for (( init; condition; increment ))
|
||||
do
|
||||
commands
|
||||
ndone
|
||||
```
|
||||
|
||||
**Example:**
|
||||
|
||||
```bash
|
||||
for (( i=0; i<5; i++ ))
|
||||
do
|
||||
echo "Index: $i"
|
||||
done
|
||||
```
|
||||
|
||||
*Output:*
|
||||
|
||||
```
|
||||
Index: 0
|
||||
Index: 1
|
||||
Index: 2
|
||||
Index: 3
|
||||
Index: 4
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Looping Over Files (Globbing)
|
||||
|
||||
Use shell glob patterns to iterate over matching filenames.
|
||||
|
||||
**Example:**
|
||||
|
||||
```bash
|
||||
for file in *.txt
|
||||
do
|
||||
echo "Found text file: $file"
|
||||
done
|
||||
```
|
||||
|
||||
```
|
||||
# If the directory contains a.txt and notes.txt, output might be:
|
||||
Found text file: a.txt
|
||||
Found text file: notes.txt
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
| Style | Purpose | Notes |
|
||||
| ----------------- | ------------------------------------------ | ------------------------------------- |
|
||||
| `for var in list` | Iterate over a static list or glob results | Most common in shell scripting |
|
||||
| `for (( ... ))` | Numeric / arithmetic loops | C-style syntax, powerful for counters |
|
||||
|
||||
138
Linux/Bash-Script/10-While.md
Normal file
138
Linux/Bash-Script/10-While.md
Normal file
@@ -0,0 +1,138 @@
|
||||
# Bash `while` Loop Guide
|
||||
|
||||
A clear, concise, and visually pleasant reference for using `while` loops in Bash.
|
||||
|
||||
---
|
||||
|
||||
## 1. Overview
|
||||
|
||||
The `while` loop in Bash repeatedly executes a block of commands **as long as a condition evaluates to true**. It is a fundamental control structure for iteration when the number of repetitions is not known in advance.
|
||||
|
||||
### General form
|
||||
|
||||
```bash
|
||||
while [ condition ]
|
||||
do
|
||||
command1
|
||||
command2
|
||||
...
|
||||
done
|
||||
```
|
||||
|
||||
* The condition is evaluated before each iteration. If it returns a zero (truthy) exit status, the loop body runs. Otherwise, the loop exits.
|
||||
* Square brackets (`[ ... ]`) are a synonym for the `test` command; spacing matters.
|
||||
|
||||
---
|
||||
|
||||
## 2. Examples
|
||||
|
||||
### 2.1 Simple counter
|
||||
|
||||
Counts from 1 to 5 and prints the current value.
|
||||
|
||||
```bash
|
||||
counter=1
|
||||
|
||||
while [ $counter -le 5 ]
|
||||
do
|
||||
echo "Counter: $counter"
|
||||
((counter++))
|
||||
done
|
||||
```
|
||||
|
||||
**What it does:**
|
||||
|
||||
* Initializes `counter` to 1.
|
||||
* The loop continues while `counter` is less than or equal to 5.
|
||||
* Prints and increments the counter each iteration.
|
||||
|
||||
### 2.2 Waiting for a file to appear
|
||||
|
||||
Polls for the existence of `/tmp/myfile.txt` once per second.
|
||||
|
||||
```bash
|
||||
while [ ! -f /tmp/myfile.txt ]
|
||||
do
|
||||
echo "Waiting for file..."
|
||||
sleep 1
|
||||
done
|
||||
|
||||
echo "File exists!"
|
||||
```
|
||||
|
||||
**What it does:**
|
||||
|
||||
* Checks if the file does **not** exist (`! -f`).
|
||||
* Sleeps for one second between checks to avoid busy-waiting.
|
||||
* When the file appears, exits the loop and prints confirmation.
|
||||
|
||||
### 2.3 Interactive prompt with exit condition
|
||||
|
||||
Keeps prompting the user until they type `q`.
|
||||
|
||||
```bash
|
||||
while true
|
||||
do
|
||||
read -p "Type 'q' to quit: " input
|
||||
if [ "$input" = "q" ]; then
|
||||
break
|
||||
fi
|
||||
done
|
||||
```
|
||||
|
||||
**What it does:**
|
||||
|
||||
* Uses an infinite loop (`while true`).
|
||||
* Prompts the user each time.
|
||||
* Exits the loop when the input equals `q` using `break`.
|
||||
|
||||
---
|
||||
|
||||
## 3. Tips & Best Practices
|
||||
|
||||
* **Quote variables** to avoid word splitting and issues when they are empty: `[ "$foo" = "bar" ]`.
|
||||
* **Use arithmetic expressions** with `(( ... ))` when dealing with numbers (`((counter++))` is more concise than `counter=$((counter + 1))`).
|
||||
* **Avoid busy loops:** if waiting on external state, insert a `sleep` to reduce CPU usage.
|
||||
* **Use `set -u` and `set -e`** in scripts to catch undefined variables and stop on errors, but be careful when using them with conditional tests.
|
||||
* **Test conditions explicitly:** e.g., use `-f`, `-d`, `-r`, `-s`, etc., for file-related checks.
|
||||
|
||||
---
|
||||
|
||||
## 4. Common Pitfalls
|
||||
|
||||
* Missing spaces inside `[ ]` — `while [$counter -le 5]` is invalid; it must be `[ $counter -le 5 ]`.
|
||||
* Forgetting to initialize loop variables, leading to unexpected behavior when using them in tests.
|
||||
* Using `read` without handling empty input; consider providing a default or validating.
|
||||
* Infinite loops without an exit strategy (e.g., missing `break` or condition never false).
|
||||
|
||||
---
|
||||
|
||||
## 5. Variations
|
||||
|
||||
* **Until loop:** opposite of `while` — runs until a condition becomes true.
|
||||
|
||||
```bash
|
||||
until [ -f /tmp/myfile.txt ]
|
||||
do
|
||||
echo "Waiting..."
|
||||
sleep 1
|
||||
```
|
||||
|
||||
done
|
||||
|
||||
- **Command-based condition:** you can use any command whose exit status matters.
|
||||
|
||||
```bash
|
||||
while ping -c1 example.com >/dev/null 2>&1
|
||||
do
|
||||
echo "Host is reachable"
|
||||
sleep 5
|
||||
done
|
||||
````
|
||||
|
||||
---
|
||||
|
||||
## 6. Summary
|
||||
|
||||
Use `while` loops when the number of iterations depends on dynamic conditions (user input, file existence, external services). Combine with proper quoting, sleeping, and exit strategies to write robust and readable scripts.
|
||||
|
||||
Reference in New Issue
Block a user