Oussama GHAIEB

Tips, tricks, and code snippets for developers

Bash Scripting for Beginners: Learn the Basics Step by Step

Bash scripting is one of the most powerful skills you can learn as a developer, DevOps engineer, or system administrator. With just a few lines of code, you can:

Automate repetitive tasks (e.g., backups, log cleaning)
Manage systems efficiently (e.g., bulk user creation)
Build small command-line tools (e.g., file renamers, log parsers)

In this guide, you’ll learn Bash scripting from scratch—no prior experience needed. We’ll cover core concepts with copy-paste examples you can modify and use immediately.


📄 What Is a Bash Script?

A Bash script is a plain text file containing commands that run in sequence—just like typing them in the terminal.

🔹 How to Create & Run a Script

  1. Write commands in a file (e.g., hello.sh):

    #!/bin/bash  # This is called the "shebang"—it tells the system to use Bash.
    echo "Hello, World!"
    
  2. Make it executable:

    chmod +x hello.sh  # Grants execute permission.
    
  3. Run it:

    ./hello.sh  # Output: "Hello, World!"
    

🔤 Bash Syntax Basics

✅ 1. Comments

Use # for single-line comments. Bash ignores text after #.

# This line is a comment.  
echo "This runs."  # This part is also ignored.

✅ 2. Variables

Store text, numbers, or command outputs. No spaces around =!

name="Oussama"  
echo "Hello, $name!"  # Output: "Hello, Oussama!"  

🔹 Best Practices:

  • Quote variables to avoid errors with spaces:
    full_name="Oussama Ghaieb"  
    echo "Hello, $full_name"  # Works!  
    
  • Use curly braces for clarity: ${variable}.

✅ 3. User Input

Use read to prompt for input:

read -p "Enter your age: " age  
echo "You are $age years old."  

✅ 4. Conditionals (if Statements)

Compare values and act accordingly:

if [ "$age" -ge 18 ]; then  # -ge = "greater or equal"  
  echo "You are an adult."  
else  
  echo "You are a minor."  
fi  

🔹 Key Rules:

  • = for strings, -eq/-lt/-gt for numbers.
  • Always put spaces inside [ ].

✅ 5. Loops

🔄 for Loop

Iterate over a list:

for fruit in "apple" "banana" "cherry"; do  
  echo "Fruit: $fruit"  
done  

🔁 while Loop

Run while a condition is true:

count=1  
while [ $count -le 3 ]; do  
  echo "Count: $count"  
  ((count++))  # Increment count  
done  

✅ 6. Functions

Group reusable code:

greet() {  
  echo "Hello, $1!"  
}  

greet "Oussama"  # Output: "Hello, Oussama!"  

🔹 Return Values:
Bash functions return exit codes. Use echo to "return" data:

add() {  
  echo $(($1 + $2))  
}  

result=$(add 5 7)  # Captures output  
echo "Sum: $result"  # Output: "Sum: 12"  

✅ 7. Arrays

Store multiple values:

fruits=("apple" "banana" "cherry")  
echo "First fruit: ${fruits[0]}"  # Output: "apple"  

Loop through an array:

for fruit in "${fruits[@]}"; do  
  echo "$fruit"  
done  

✅ 8. Exit Codes

0 = success, 1-255 = error. Check command success:

if ! command -v git &> /dev/null; then  
  echo "Error: Git is not installed."  
  exit 1  
fi  

✅ 9. Command Substitution

Run a command and store its output:

current_date=$(date)  
echo "Today is $current_date"  

🧪 Practical Example: Automated Backup Script

#!/bin/bash  

# Create a backup directory with today's date  
backup_dir="/tmp/backup_$(date +%Y%m%d)"  
mkdir -p "$backup_dir"  

# Copy important files  
cp -r ~/documents "$backup_dir"  

echo "Backup saved to: $backup_dir"  

Run it:

chmod +x backup.sh  
./backup.sh  

🎓 Pro Tips for Bash Scripting

  1. Debug with bash -x script.sh (prints each command before running).
  2. Use set -e to exit on errors.
  3. Always quote variables ("$var") to avoid word splitting.
  4. Check for dependencies at script start (e.g., curl, git).

🚀 What’s Next?

  • Learn awk and sed for text processing.
  • Explore cron jobs to schedule scripts.
  • Try writing a log analyzer or file organizer.

Bash is preinstalled on Linux/macOS, and mastering it unlocks unlimited automation power. Start small, experiment often, and happy scripting! 🐧

Tags: #bash #shell
Oussama GHAIEB - Laravel Certified Developer in Paris

Oussama GHAIEB

Laravel Certified Developer | Full-Stack Web Developer in Paris

14+ years experience 20+ projects
Read more about me →

Comments (0)

No comments yet. Be the first to comment!


Leave a Comment

More Posts :