🖥️ Bash Scripting Basics 🖥️
🎯 Script Debugging Mode
#!/bin/bash
# Enable debugging
set -x
echo "Start of the script"
var="Bash scripting"
echo "Learning $var"Explanation:
set -xenables debugging mode, showing each command and its arguments as they are executed.
🚨 Error Handling
#!/bin/bash
# Exit on error
set -e
echo "This will run"
non_existing_command
echo "This will not run"Explanation:
set -ecauses the script to exit immediately if any command returns a non-zero exit status.
🔄 Using if Statements
if [ $? -ne 0 ]; then
echo "Last command failed!"
fiExplanation:
$?holds the exit status of the last command.-ne 0checks if the status is not equal to 0, indicating an error.
🔧 Logging and Output
#!/bin/bash
set -x
logfile="script.log"
log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> $logfile
}
log "Script started"
log "Processing data"
echo " Echo is different from log "
log "Script ended"Explanation:
- Logs are written to
script.logwith timestamps.
🔄 Control Structures
If Statements
if [ condition ]; then
# code
elif [ another_condition ]; then
# code
else
# code
fiFor Loops
# Basic For Loop
for i in {1..5}; do
echo "Iteration $i"
done
# Advanced For Loop
for (( i = 0 ; i <= 5; i++ ))
do
echo "Welcome $i times"
doneWhile Loop
while [ condition ]; do
# code
doneFunctions
function greet() {
echo "Hello, $1"
}
greet "World"📁 File Operations
if [ -f "file.txt" ]; then
echo "File exists."
else
echo "File does not exist."
fiExplanation:
- Checks if a file exists before performing operations.
🧩 Case Statements
#!/bin/bash
read -p "Enter a letter: " letter
case $letter in
[a-z])
echo "You entered a lowercase letter"
;;
[A-Z])
echo "You entered an uppercase letter"
;;
[0-9])
echo "You entered a number"
;;
*)
echo "You entered a special character"
;;
esac🍎 Arrays
#!/bin/bash
fruits=("apple" "banana" "cherry")
for fruit in "${fruits[@]}"; do
echo "I like $fruit"
done🌐 HTTP Requests
#!/bin/bash
response=$(curl -s -w "%{http_code}" -o response.txt http://example.com)
echo "HTTP Status Code: $response"🗓️ Date and Time
echo "Today is date"
echo "Today is `date`"Explanation:
- Uses the
datecommand to print the current date.
📝 Reading User Input
#!/bin/bash
read -p "Enter your name: " name
echo "Hello, $name!"📜 Comments and Formatting
#!/bin/bash
echo "Hello, World!" # This is a comment
MANGO=4
APPLE="3"
BUCKET="Total of 5 Bucket"
echo "Today I have sold $MANGO & $APPLE" \a "$BUCKET"Explanation:
\aproduces an alert sound.- Comments are preceded by
#.
⏳ Running Commands with sleep
#!/bin/bash
echo "Running command 1..."
sleep 1
echo "Running command 2..."
sleep 1
# Prompt the user for input
read -p "Do you want to execute command 6? (yes/no): " user_input
# Convert user input to lowercase
user_input=$(echo "$user_input" | tr '[:upper:]' '[:lower:]')
if [[ $user_input == "yes" || $user_input == "y" ]]; then
echo "Running command 6..."
sleep 1
else
echo "Skipping command 6..."
fi
echo "All commands executed."