Skip to content

Input Parameter Parsing in Bash #806

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 146 additions & 0 deletions tutorials/learnshell.org/en/Input Parameter Parsing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
**Input Parsing Parameters in Bash**

---

Bash scripts are incredibly useful for automating tasks in Linux environments. Often, you'll need to create scripts that accept input parameters. In this tutorial, we'll cover how to parse input parameters in a Bash script using `getopts`.

---

### **Tutorial**

Bash provides the `getopts` built-in for parsing options and arguments. Options typically begin with a hyphen (`-`) and can be combined together. For example, `-a -b -c` can be combined as `-abc`. We’ll also show how to handle optional arguments using `getopts`.

In this tutorial, you'll learn:
- How to parse short options like `-a`, `-b` using `getopts`.
- How to handle required and optional arguments.
- How to handle invalid options.

#### **How `getopts` Works**

The basic syntax for `getopts` is:
```bash
while getopts "abc:" opt; do
case $opt in
a)
echo "Option a was triggered"
;;
b)
echo "Option b was triggered"
;;
c)
echo "Option c was triggered with argument: $OPTARG"
;;
\?)
echo "Invalid option: -$OPTARG" >&2
;;
esac
done
```

- The string `"abc:"` indicates that options `-a`, `-b` do not require an argument, while `-c` requires an argument (indicated by the colon).
- `$OPTARG` stores the argument provided for options that require one.

---

### **Exercise**

Create a Bash script that accepts three options: `-n`, `-u`, and `-f`, where:
- `-n` requires a name (string argument).
- `-u` is a flag that converts the name to uppercase.
- `-f` is a flag that converts the name to lowercase.

**Objective**: Write a script that parses the options and prints the modified name according to the flags.

---

### **Tutorial Code**

Here is a starting point for your script:
```bash
#!/bin/bash

while getopts "n:uf" opt; do
case $opt in
n)
name=$OPTARG
;;
u)
to_upper=true
;;
f)
to_lower=true
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
esac
done

# Your logic here for converting the name
```

---

### **Expected Output**

If the script is run as:
```bash
./myscript.sh -n "John Doe" -u
```

The output should be:
```
JOHN DOE
```

If the script is run as:
```bash
./myscript.sh -n "John Doe" -f
```

The output should be:
```
john doe
```

---

### **Solution**

Here is a complete solution for the exercise:
```bash
#!/bin/bash

while getopts "n:uf" opt; do
case $opt in
n)
name=$OPTARG
;;
u)
to_upper=true
;;
f)
to_lower=true
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
esac
done

# Apply transformations based on flags
if [ "$to_upper" = true ]; then
name=$(echo "$name" | tr '[:lower:]' '[:upper:]')
elif [ "$to_lower" = true ]; then
name=$(echo "$name" | tr '[:upper:]' '[:lower:]')
fi

echo "$name"
```

---

This tutorial shows how to parse input parameters in Bash and apply transformations based on the provided options. By following the structure, you can extend this logic to more complex scenarios in your Bash scripts.

122 changes: 122 additions & 0 deletions tutorials/learnshell.org/en/Regular Expressions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@

---

**Using Regular Expressions (Regex) in Bash**

---

Regular expressions (regex) are powerful tools for matching patterns within strings. In Bash, regex is often used in combination with tools like `grep`, `sed`, and within conditional statements using `[[ ]]`. In this tutorial, we'll explore how to use regex in Bash scripts effectively.

---

### **Tutorial**

A regular expression defines a search pattern that can be used to match strings. In Bash, regex is primarily used for:
- Validating input (e.g., ensuring an email format).
- Extracting parts of a string based on patterns.
- Searching and replacing text.

This tutorial covers:
- Basic regex syntax in Bash.
- How to use regex within `[[ ]]` and `grep`.
- Handling regex in scripts for different tasks like pattern matching and input validation.

#### **Regex Syntax Overview**

Here are some common regex patterns:
- `^`: Matches the beginning of a string.
- `$`: Matches the end of a string.
- `.`: Matches any single character.
- `[abc]`: Matches any character `a`, `b`, or `c`.
- `*`: Matches zero or more occurrences of the preceding character.
- `+`: Matches one or more occurrences of the preceding character.

For example, the pattern `^[a-zA-Z]+$` matches a string containing only alphabetic characters.

#### **Using Regex in Bash**

In Bash, you can use regex within `[[ ]]` for pattern matching:
```bash
if [[ "Hello123" =~ ^[A-Za-z]+$ ]]; then
echo "Only letters found!"
else
echo "Contains non-letter characters."
fi
```
In the above code:
- The pattern `^[A-Za-z]+$` checks if the string contains only letters.

---

### **Exercise**

Create a Bash script that:
- Accepts a string as input.
- Validates if the string is a valid email address using regex.
- If the input is a valid email, print "Valid email". Otherwise, print "Invalid email".

**Hint:** A basic regex for an email can be something like `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`.

---

### **Tutorial Code**

Start with the following code:
```bash
#!/bin/bash

read -p "Enter your email: " email

if # add you statement here; then
# add a if else condition and print out the changes
fi
```

---

### **Expected Output**

When the script is run:
```bash
./validate_email.sh
```

For the input:
```
Enter your email: [email protected]
```
The expected output is:
```
Valid email
```

For an invalid email input:
```
Enter your email: user@invalid
```
The output should be:
```
Invalid email
```

---

### **Solution**

Here’s the complete solution:
```bash
#!/bin/bash

read -p "Enter your email: " email

# Regex to validate an email address
if [[ $email =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
echo "Valid email"
else
echo "Invalid email"
fi
```

---

This tutorial gives you a solid foundation in using regex in Bash for pattern matching and validation. Regex is a powerful tool that, when combined with Bash scripting, can automate many text-processing tasks.
Loading