مبتدی 45 دقیقه 2024/01/10

Bash Scripting: راهنمای مبتدیان

راهنمای جامع برای مبتدیان مطلق در اسکریپت‌نویسی bash. متغیرها، شرطی‌ها، حلقه‌ها و توابع را یاد بگیرید.

bash مبانی اسکریپت‌نویسی shell script آموزش لینوکس

What is Bash Scripting?

Bash (Bourne Again Shell) is a powerful tool used as command-line interface and scripting language on Linux and Unix systems.

Your First Bash Script

Let's start with a simple "Hello World" script:

#!/bin/bash
echo "Hello World!"

Variables

Defining and using variables in Bash:

#!/bin/bash
NAME="John"
AGE=25

echo "Hello, my name is $NAME"
echo "My age: $AGE"

User Input

#!/bin/bash
read -p "Enter your name: " USERNAME
echo "Hello $USERNAME!"

Conditional Statements (if-else)

#!/bin/bash
read -p "Enter a number: " NUMBER

if [ $NUMBER -gt 10 ]; then
    echo "Number is greater than 10"
elif [ $NUMBER -eq 10 ]; then
    echo "Number equals 10"
else
    echo "Number is less than 10"
fi

Loops

For Loop:

#!/bin/bash
for i in {1..5}; do
    echo "Number: $i"
done

While Loop:

#!/bin/bash
COUNTER=1
while [ $COUNTER -le 5 ]; do
    echo "Counter: $COUNTER"
    ((COUNTER++))
done

Functions

#!/bin/bash

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

# Call function
greet "World"
greet "Linux"

Practical Examples

System Backup Script:

#!/bin/bash
SOURCE="/home/user/documents"
DEST="/backup/$(date +%Y%m%d)"

mkdir -p "$DEST"
cp -r "$SOURCE" "$DEST"

echo "Backup completed: $DEST"

Exercises

  1. Write a script that takes two numbers and adds them
  2. Script that prints even numbers from 1 to 100
  3. List all .txt files in a directory
  4. Create a simple calculator (+, -, *, /)