1. Introduction to Bash Scripting
Bash (Bourne Again SHell) is a command-line interface and scripting language used in many Unix-like operating systems. Bash scripts allow you to automate tasks, create custom commands, and build powerful utilities.
2. Creating Your First Bash Script
To create a bash script:
- Open a text editor
- Start the file with a shebang: #!/bin/bash
- Write your commands
- Save the file with a .sh extension
- Make the file executable using chmod +x filename.sh
#!/bin/bash
echo "Hello, World!"
3. Variables
Variables in bash are created by assigning a value to a name. Use them by prefixing the name with a $ sign.
#!/bin/bash
name="John"
echo "Hello, $name!"
4. User Input
Use the read command to get input from the user.
#!/bin/bash
echo "What's your name?"
read name
echo "Hello, $name!"
5. Conditional Statements
Use if, elif, and else for conditional execution.
#!/bin/bash
age=25
if [ $age -lt 18 ]
then
echo "You are a minor."
elif [ $age -ge 18 ] && [ $age -lt 65 ]
then
echo "You are an adult."
else
echo "You are a senior citizen."
fi
6. Loops
Bash supports for, while, and until loops.
#!/bin/bash
# For loop
for i in 1 2 3 4 5
do
echo "Number: $i"
done
# While loop
count=0
while [ $count -lt 5 ]
do
echo "Count: $count"
count=$((count+1))
done
7. Functions
Functions allow you to group commands for reuse.
#!/bin/bash
greet() {
echo "Hello, $1!"
}
greet "Alice"
greet "Bob"
8. Command-Line Arguments
Access command-line arguments using $1, $2, etc. $0 is the script name.
#!/bin/bash
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
echo "All arguments: $@"
9. Exit Status
Commands return an exit status (0 for success, non-zero for failure). Access the last command's exit status with $?.
#!/bin/bash
ls /nonexistent
if [ $? -eq 0 ]
then
echo "Command succeeded"
else
echo "Command failed"
fi
Tip:
Always use double quotes around variables to prevent word splitting and globbing.
echo "$variable" # Correct
echo $variable # Potentially problematic
10. Debugging Bash Scripts
Use set -x to enable debugging mode, which prints each command before executing it.
#!/bin/bash
set -x # Enable debugging
name="Alice"
echo "Hello, $name!"
set +x # Disable debugging
Further Learning
To advance your Bash scripting skills, consider exploring: