π Shell Scripting Challenge.
Learn essential Bash scripting skills through a step-by-step challenge, from variables to wildcards.
Shell scripting is a powerful way to automate tasks and manage systems efficiently. This challenge covers essential Bash scripting concepts like comments, variables, built-in variables, and wildcards.
π Understanding the Challenge
Hereβs what weβll cover in our script:
β
Comments (#
) β Add explanatory notes in the script.
β
Echo (echo
) β Display messages in the terminal.
β
Variables (var=value
) β Store and manage data.
β
Using Variables ($((expression))
) β Perform operations using stored values.
β
Built-in Variables ($USER, $HOME, $PWD, $SHELL, $HOSTNAME, $OSTYPE
) β Access system information.
β
Wildcards (*.txt, ?file.*, [abc]*.sh
) β List files with a specific pattern.
π The Complete Shell Script
#!/bin/bash
# ====Task 1: Comments ====
# This script demonstrates various shell scripting concepts.
# ====Task 2: Echo ====
echo "Welcome to the Shell Scripting Challenge!"
# ====Task 3: Variables ====
name="Bash Scripting"
age=10
# Displaying variable values
echo "Topic: $name"
echo "Years of Experience: $age"
# ====Task 4: Using Variables (Simple Addition) ====
num1=10
num2=20
sum=$((num1 + num2))
echo "The sum of $num1 and $num2 is $sum"
# ====Task 5: Using Built-in Variables ====
echo "Current User: $USER"
echo "Home Directory: $HOME"
echo "Current Working Directory: $PWD"
echo "Current Shell: $SHELL"
echo "Hostname: $HOSTNAME"
echo "Operating System Type: $OSTYPE"
echo "Current Date and Time: $(date)"
echo "System Uptime: $(uptime -p)"
echo "Current Logged-in Users: $(who)"
# ====Task 6: Wildcards (Listing files based on patterns)====
echo "Listing all .txt files in the current directory:"
ls *.txt # Lists all text files
echo "Listing all .sh files that start with 'script':"
ls script*.sh # Lists all shell scripts starting with "script"
echo "Listing all files that start with any letter a, b, or c and end with .sh:"
ls [abc]*.sh # Lists all shell scripts starting with a, b, or c
echo "Listing all files with any single character before 'file' and any extension:"
ls ?file.* # Lists files like 'afile.txt', 'bfile.csv'
π Breaking Down the Script
π Shebang (#!/bin/bash
) β Defines the script interpreter.
π Comments (#
) β Used to add explanations.
π Echo (echo "text"
) β Prints messages to the terminal.
π Variables (var=value
) β Stores data.
π Arithmetic Operations ($((expression))
) β Performs calculations.
π Built-in Variables ($USER, $HOME, $PWD, $SHELL, $HOSTNAME, $OSTYPE
) β Displays system info.
π Wildcards (*.txt, script*.sh, [abc]*.sh, ?file.*
) β Lists specific files.
π How to Run the Script
1οΈβ£ Open a terminal and navigate to the script location.
2οΈβ£ Make the script executable:
chmod +x script.sh
3οΈβ£ Run the script:
./script.sh