Shell Scripting Basics
Introduction
Shell scripting is a powerful tool in the Linux environment that allows users to automate tasks, manage system operations, and streamline workflows. This tutorial will guide you through the basics of shell scripting, from simple commands to writing full scripts.
What is a Shell?
A shell is a command-line interpreter that provides a user interface for the Unix operating system. The most common shell is Bash (Bourne Again SHell).
Creating Your First Script
To create a shell script, you simply create a text file with the commands you want to execute. Let's start with a simple example:
echo "Hello, World!"
Save this file as hello.sh
and make it executable by running the following command:
Now you can run your script:
Variables
Variables in bash are used to store information that can be referenced later in the script.
NAME="John"
echo "Hello, $NAME"
Conditional Statements
Bash supports conditional statements like if-else to perform different actions based on conditions.
if [ "$1" -gt 100 ]
then
echo "The number is greater than 100"
else
echo "The number is less than or equal to 100"
fi
Loops
Loops allow you to iterate over a series of commands. The two most common types are for and while loops.
For Loop
for i in 1 2 3 4 5
do
echo "Welcome $i times"
done
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times
While Loop
COUNTER=0
while [ $COUNTER -lt 5 ]
do
echo "Count: $COUNTER"
COUNTER=$((COUNTER + 1))
done
Count: 1
Count: 2
Count: 3
Count: 4
Functions
Functions are used to group commands into a single, reusable unit. They make scripts easier to read and maintain.
function greet {
echo "Hello, $1"
}
greet "Alice"
greet "Bob"
Hello, Bob
Conclusion
This tutorial covered the basics of shell scripting, including creating scripts, using variables, conditional statements, loops, and functions. With these fundamentals, you can start automating tasks and improving your productivity in the Linux environment.