Bash (Bourne Again Shell) is a command language interpreter for Unix and Unix-like operating systems. It is widely used for automating tasks, writing system administration scripts, and more. In this tutorial, we’ll cover the basics of Bash scripting step by step.
Prerequisites
Before getting started, ensure you have:
- Access to a Unix or Unix-like operating system (Linux, macOS, etc.).
- A text editor like Vim, Nano, or Visual Studio Code.
- Basic knowledge of Unix/Linux command-line operations.
Step 1: Creating Your First Script
- Open your preferred text editor.
- Create a new file with a
.sh
extension (e.g.,myscript.sh
). - Add the following line at the beginning of the script to specify the interpreter:
#!/bin/bash
- Write your script below this line.
Step 2: Hello World Script
Let’s start with a simple “Hello, World!” script.
#!/bin/bash
echo "Hello, World!"
Step 3: Running Your Script
After saving your script, you need to make it executable.
chmod +x myscript.sh
Now, you can run your script:
./myscript.sh
You should see the output: Hello, World!
Step 4: Variables and User Input
Bash allows you to use variables to store data. You can also read input from users.
#!/bin/bash
# Define a variable
name="John"
# Read input from user
echo "Enter your age:"
read age
# Print a message using variables
echo "Hello, $name! You are $age years old."
Step 5: Conditional Statements
Bash supports conditional statements like if
, elif
, and else
.
#!/bin/bash
echo "Enter a number:"
read num
if [ $num -gt 0 ]; then
echo "The number is positive."
elif [ $num -lt 0 ]; then
echo "The number is negative."
else
echo "The number is zero."
fi
Step 6: Loops
You can use loops in Bash like for
and while
.
#!/bin/bash
# For loop
echo "Counting to 5:"
for i in {1..5}; do
echo $i
done
# While loop
echo "Counting down from 5:"
num=5
while [ $num -gt 0 ]; do
echo $num
((num--))
done
Conclusion
With these fundamentals, you can start automating tasks, writing more complex scripts, and exploring advanced Bash features. Keep practicing and experimenting to become proficient in Bash scripting.