Shell scripting is a powerful and versatile way to interact with your computer's operating system. It allows you to automate tasks, perform system operations, and create customized programs. In this article, we will explore the fundamentals of shell scripting and delve into various operations and constructs you can use.
Variables
In shell scripting, variables are used to store data, and they can be categorized into two types:
Simple Variables
Simple variables are assigned values without spaces. For example:
first_name="Aqib"
Variables with Spaces
If you want to store a value with spaces, enclose it in double quotes:
first_name="Aqib without space"
Parameters
Parameters provide a way to pass values to a script. The $(pwd)
command returns the current working directory, and $?
holds the exit status of the last executed command.
current_directory=$(pwd)
echo "Current directory: $current_directory"
echo "Exit status: $?"
Conditional Statements
Shell scripting supports conditional statements for decision-making. Here are some common comparisons:
-eq
: Equal to-ne
: Not equal to-lt
: Less than-le
: Less than or equal to-gt
: Greater than-ge
: Greater than or equal to
Conditional constructs like if
and elif
are used to make decisions based on these comparisons.
#!/bin/bash
# Define two numbers
number1=10
number2=20
# Perform comparisons and display results
if [ $number1 -eq $number2 ]; then
echo "$number1 is equal to $number2"
fi
if [ $number1 -ne $number2 ]; then
echo "$number1 is not equal to $number2"
fi
if [ $number1 -lt $number2 ]; then
echo "$number1 is less than $number2"
fi
if [ $number1 -le $number2 ]; then
echo "$number1 is less than or equal to $number2"
fi
if [ $number1 -gt $number2 ]; then
echo "$number1 is greater than $number2"
fi
if [ $number1 -ge $number2 ]; then
echo "$number1 is greater than or equal to $number2"
fi
in this script:
We define two numbers,
number1
andnumber2
.We use the comparison operators you mentioned (-eq, -ne, -lt, -le, -gt, -ge) to compare the values of
number1
andnumber2
.If a comparison is true, the script displays a corresponding message using
echo
.
When you run this script, it will compare the two numbers and display messages based on the results of the comparisons. The output will indicate which comparisons are true or false.
output:
While Loop:
A while loop repeatedly executes a block of code as long as a specified condition is true. Here's the basic structure of a while loop:
while [condition]
do
# Code to be executed as long as the condition is true
done
For Loop:
A for loop is used to iterate over a list of items or a sequence of numbers. It executes a block of code for each item in the list or each number in the sequence. Here's the basic structure of a for loop:
for variable in list
do
# Code to be executed for each item in the list
done
Break Statement:
The break
statement is used to exit a loop prematurely. It can be used inside both while and for loops to break out of the loop based on a certain condition.
Continue Statement:
The continue
statement is used to skip the current iteration of a loop and move to the next iteration. It's often used when a certain condition is met and you want to continue with the next iteration.
Example script used all these concepts:
#!/bin/bash
# Example of a while loop
count=1
while [ $count -le 5 ]
do
echo "While Loop: Iteration $count"
count=$((count + 1))
done
# Example of a for loop
fruits=("Apple" "Banana" "Cherry" "Date" "Fig")
for fruit in "${fruits[@]}"
do
echo "For Loop: $fruit"
done
# Example of a loop with break and continue statements
echo "Loop with Break and Continue:"
for number in {1..10}
do
if [ $number -eq 5 ]; then
echo "Encountered 5. Breaking loop."
break
elif [ $number -eq 3 ]; then
echo "Skipping 3. Continuing to the next iteration."
continue
else
echo "Current number: $number"
fi
done
In this script:
We use a while loop to print a message for each of the first 5 iterations.
We use a for loop to iterate over a list of fruits and print each fruit's name.
We demonstrate the use of break and continue statements inside a loop, with the loop breaking when the number 5 is encountered and skipping the number 3.
File Operations
Shell scripting provides methods to read from and write to files. The cat
command can be used to read a file, and the echo
command can append to a file.
# Read a file
cat file.txt
# Write to a file
echo "Hello, World!" > output.txt
Lab Exercise: Automating Directory Cleanup
In this lab exercise, we'll create a simple shell script that automates directory cleanup by moving older files to an archive directory. You can apply your scripting skills to keep your directories organized and clutter-free.
Objective: Create a shell script that identifies and moves files in the current directory that are older than a specified number of days into an "archive" directory.
Instructions: Follow the detailed instructions in the article to create a directory cleanup script. This exercise demonstrates the practical use of shell scripting and reinforces your understanding of variables, conditional statements, loops, functions, pipes, and file operations.
#!/bin/bash
# Set the source directory, archive directory, and the number of days
source_directory="./source"
archive_directory="./archive"
days_threshold=30
# Create the archive directory if it doesn't exist
if [ ! -d "$archive_directory" ]; then
mkdir -p "$archive_directory"
echo "Created archive directory: $archive_directory"
fi
# Use the find command to identify and move files older than the specified number of days
find "$source_directory" -type f -mtime +$days_threshold -exec mv {} "$archive_directory" \;
# Display a message to indicate that the cleanup process is complete
echo "Cleanup complete. Files older than $days_threshold days have been moved to $archive_directory."
In this script:
We set the source directory, archive directory, and the number of days as variables, which you can customize according to your needs.
We use the
if
statement to check if the "archive" directory exists, and if not, we create it usingmkdir
.We use the
find
command to identify files in the source directory that are older than the specified number of days and then move them to the archive directory.Finally, we display a message indicating that the cleanup process is complete.
You can change the source_directory
, archive_directory
, and days_threshold
variables to match your specific use case. This script demonstrates how to automate directory cleanup using shell scripting, reinforcing your knowledge of variables, conditional statements, and file operations.
Thank you for reading this article