LWM-Linux/07 - Shell Scripting Basics/Bash Scripting Basics.md

130 lines
2.1 KiB
Markdown
Raw Permalink Normal View History

# Introduction to Bash Scripting
Bash (Bourne Again SHell) is a command-line interface and scripting language used in Unix and Unix-like operating systems, including Linux and macOS. Bash scripts are text files containing a series of commands that can be executed by the Bash shell.
## 1. Creating a Bash Script
To create a Bash script:
- Open a text editor
2024-09-07 10:14:32 -06:00
- Start the file with a shebang: #!/bin/bash # This line tells the shell what to use as the interpreter. Can be bash, python, etc...
- Add your commands
- Save the file with a .sh extension (e.g., myscript.sh)
- Make the script executable: chmod +x myscript.sh
Here's a simple example:
```bash
#!/bin/bash
echo "Hello, World!"
```
## 2. Variables
Variables in Bash are created by assigning a value:
2024-09-07 10:14:32 -06:00
```
name="John"
age=30
echo "Name: $name, Age: $age"
```
Use `$` to reference variables. For command substitution, use `$(command)`:
2024-09-07 10:14:32 -06:00
```
current_date=$(date +%Y-%m-%d)
echo "Today is $current_date"
```
2024-09-07 10:14:32 -06:00
- Output: Today is 2024-09-07
## 3. User Input
Use `read` to get user input:
2024-09-07 10:14:32 -06:00
```
echo "What's your name?"
read user_name
echo "Hello, $user_name!"
```
## 4. Conditional Statements
If-else statements:
2024-09-07 10:14:32 -06:00
```
if [ "$age" -ge 18 ]; then
echo "You are an adult"
else
echo "You are a minor"
fi
```
Note the spaces around the brackets and comparison operator.
## 5. Loops
For loop:
2024-09-07 10:14:32 -06:00
```
for i in {1..5}
do
2024-09-07 10:14:32 -06:00
echo "Iteration $i"
done
```
While loop:
2024-09-07 10:14:32 -06:00
```
counter=1
while [ $counter -le 5 ]
do
2024-09-07 10:14:32 -06:00
echo "Counter: $counter"
((counter++))
done
```
## 6. Functions
Define and call functions:
2024-09-07 10:14:32 -06:00
```
greet() {
2024-09-07 10:14:32 -06:00
echo "Hello, $1!" # $1 takes the first argument passed after the function
}
greet "Alice"
greet "Bob"
```
## 7. Command-line Arguments
Access command-line arguments using `$1`, `$2`, etc.:
2024-09-07 10:14:32 -06:00
```
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
echo "All arguments: $@"
```
## 8. File Operations
Check if a file exists:
2024-09-07 10:14:32 -06:00
```
if [ -f "myfile.txt" ]; then
2024-09-07 10:14:32 -06:00
echo "myfile.txt exists"
else
2024-09-07 10:14:32 -06:00
echo "myfile.txt does not exist"
fi
```
Read from a file:
2024-09-07 10:14:32 -06:00
```
while IFS= read -r line
do
2024-09-07 10:14:32 -06:00
echo "$line"
done < "myfile.txt"
```