SyntaxStudy
Sign Up
Linux / Bash Beginner 15 min read

Bash Scripting

Bash scripting lets you automate repetitive tasks by writing sequences of commands in a file. Shell scripts are executed by the Bash interpreter.

Example
#!/bin/bash
# Shebang: tells the OS to use bash to run this script
# Make executable: chmod +x script.sh
# Run: ./script.sh

# Variables
NAME="Alice"
AGE=30
echo "Hello, $NAME! You are $AGE years old."

# User input
read -p "Enter your name: " USER_NAME
echo "Welcome, $USER_NAME!"

# Conditionals
if [ $AGE -ge 18 ]; then
  echo "Adult"
elif [ $AGE -ge 13 ]; then
  echo "Teenager"
else
  echo "Child"
fi

# For loop
for FILE in *.txt; do
  echo "Processing: $FILE"
  wc -l "$FILE"  # count lines
done

# While loop
COUNT=1
while [ $COUNT -le 5 ]; do
  echo "Count: $COUNT"
  ((COUNT++))
done

# Functions
backup_file() {
  local FILE="$1"
  cp "$FILE" "$FILE.bak"
  echo "Backed up $FILE"
}
backup_file "important.conf"