Files
my-docs/Linux/Bash Script/06-Read.md
2025-08-03 00:47:45 +03:30

78 lines
1.7 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 📝 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 users 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.