Welcome to the world of Bash scripting! This tutorial is designed for new users who want to learn how to automate tasks using Bash, the command-line shell used in most Linux and macOS systems. Bash is a powerful tool that can help you streamline repetitive tasks and manage your system more efficiently.
Bash (Bourne-Again Shell) is a command-line interpreter that allows you to interact with your operating system. It's used for:
On Linux: Use your terminal (e.g., GNOME Terminal, Konsole, etc.) On macOS: Open "Terminal" from Applications On Windows 10/11: Use "Windows Terminal" or "PowerShell" (Bash is pre-installed)
Open your terminal and type:
echo "Hello, World!"
Press Enter. You should see:
Hello, World!
This is your first Bash command! echo is a built-in command that prints text to the screen.
In Bash, you can store values in variables without declaring their type.
name="Alice" echo "Hello, $name!"
Output:
Hello, Alice!
You can run any command in Bash, like ls (list files), cd (change directory), mkdir (make directory), etc.
ls cd Desktop mkdir my_folder
for i in {1..5}; do
echo "Number: $i"
done
Output:
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5
count=0
while [ $count -lt 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
Output:
Count: 0 Count: 1 Count: 2 Count: 3 Count: 4
touch my_file.txt
ls
cat my_file.txt
mv my_file.txt new_file.txt
rm new_file.txt
You can perform arithmetic operations in Bash using $((...)):
a=10 b=5 echo "Addition: $((a + b))" echo "Subtraction: $((a - b))" echo "Multiplication: $((a * b))" echo "Division: $((a / b))"
Output:
Addition: 15 Subtraction: 5 Multiplication: 50 Division: 2
You can add comments to your script using #:
# This is a comment echo "This line is executed"
nano hello_script.sh
The shebang line tells the system which interpreter to use:
#!/bin/bash echo "Hello, World!"
chmod +x hello_script.sh
./hello_script.sh
Output:
Hello, World!
Try these simple exercises to reinforce your learning:
I wrote a flashcard game in python for learning bash commands, you can download it here.
Once you download it use this command to start it: python3 bashcommands.py
Now that you've learned the basics, you can explore:
You've taken your first steps into the world of Bash scripting. Keep practicing, and you'll be amazed at what you can build with Bash! If you have any questions or need help with anything, feel free to ask!
Happy scripting!