Shell Scripting Tutorial: A Beginner's Guide
This tutorial will guide you through the basics of shell scripting with examples and explanations.
What is Shell Scripting?
A shell script is a text file containing a sequence of commands for a Unix-based operating system. It automates repetitive tasks, simplifies complex operations, and can be used to set up and configure systems. Shell scripting is a powerful tool for automating tasks and managing system operations in Linux.
What is the Shebang?
The shebang (#!/bin/bash
) is the first line in a shell script. It tells the operating system which interpreter to use to execute the script. The #!/bin/bash
indicates that the script should be run with the Bash shell. Other common interpreters include #!/bin/sh
for the Bourne shell, #!/usr/bin/python
for Python, and #!/usr/bin/env node
for Node.js.
Getting Started
To create and run a shell script, follow these steps:
Open a text editor (like
nano
,vim
, orgedit
).Write the script.
Save the file with a
.sh
extension.Make the script executable.
Run the script.
Writing Your First Shell Script
Let's start with a simple "Hello, World!" script.
Example 1: Hello, World!
Open a text editor and write the following:
#!/bin/bash echo "Hello, World!"
#!/bin/bash
: This is called a shebang. It tells the system which interpreter to use to execute the script.echo "Hello, World!"
: This command prints "Hello, World!" to the terminal.
Save the file as
hello.sh
.Make the script executable:
chmod +x hello.sh
Run the script:
./hello.sh
Example 2: Greetings
#!/bin/bash
echo "Enter your name:"
read name
echo "Hello, $name!"
read name
: Reads user input and stores it in the variablename
.echo "Hello, $name!"
: Prints "Hello," followed by the user's name.NOTE : If the error ocurres like this
bash: ./
greetings.sh
: Permission denied
, then runchmod 777 greetings.sh
The chmod 777 command in Linux changes the permissions of a file or directory to be readable, writable, and executable by the owner, group, and all other users in the system.
Example 3: Date and Time
#!/bin/bash
echo "The current date and time is:"
date
date
: Prints the current date and time.
Variables
Variables in shell scripts store data that can be used later. You don't need to declare a variable type.
Example 1: Using Variables
#!/bin/bash
name="John Doe"
echo "Hello, $name!"
name="John Doe"
: Assigns the value "John Doe" to the variablename
.echo "Hello, $name!"
: Prints "Hello, John Doe!" to the terminal. Note the use of$
to reference the variable.
Example 2: Arithmetic Operations
#!/bin/bash
a=10
b=5
sum=$((a + b))
echo "Sum: $sum"
sum=$((a + b))
: Calculates the sum ofa
andb
and stores it in the variablesum
.echo "Sum: $sum"
: Prints the sum.
Example 3: String Concatenation
#!/bin/bash
greeting="Hello"
name="Alice"
message="$greeting, $name!"
echo $message
message="$greeting, $name!"
: Concatenates the strings and stores them in the variablemessage
.echo $message
: Prints the message.
Conditional Statements
Conditional statements control the flow of a script based on certain conditions.
Example 1: If-Else Statement
#!/bin/bash
echo "Enter your age:"
read age
if [ $age -ge 18 ]; then
echo "You are an adult."
else
echo "You are a minor."
fi
read age
: Takes user input and stores it in the variableage
.if [ $age -ge 18 ]; then ... fi
: Checks ifage
is greater than or equal to 18 and prints an appropriate message.
Example 2: Checking File Existence
#!/bin/bash
file="sample.txt"
if [ -f $file ]; then
echo "File exists."
else
echo "File does not exist."
fi
if [ -f $file ]; then ... fi
: Checks ifsample.txt
exists and prints a message accordingly.
Example 3: Comparing Strings
#!/bin/bash
string1="Hello"
string2="World"
if [ "$string1" = "$string2" ]; then
echo "Strings are equal."
else
echo "Strings are not equal."
fi
if [ "$string1" = "$string2" ]; then ... fi
: Compares the strings and prints a message accordingly.
Loops
Loops allow you to repeat a block of code multiple times.
Example 1: For Loop
#!/bin/bash
for i in 1 2 3 4 5; do
echo "Number: $i"
done
for i in 1 2 3 4 5; do ... done
: Iterates over the numbers 1 to 5 and prints each number.
Example 2: While Loop
#!/bin/bash
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
count=1
: Initializes the variablecount
to 1.while [ $count -le 5 ]; do ... done
: Repeats the loop as long ascount
is less than or equal to 5.
Example 3: Looping Through Files
#!/bin/bash
for file in *.txt; do
echo "Processing $file"
done
for file in *.txt; do ... done
: Iterates over all.txt
files in the current directory and prints a message for each file.
Functions
Functions are reusable blocks of code that perform specific tasks.
Example 1: Defining and Calling a Function
#!/bin/bash
greet() {
echo "Hello, $1!"
}
greet "Alice"
greet "Bob"
greet() { ... }
: Defines a function namedgreet
.echo "Hello, $1!"
: Prints "Hello," followed by the first argument passed to the function.greet "Alice"
andgreet "Bob"
: Calls thegreet
function with "Alice" and "Bob" as arguments.
Example 2: Sum Function
#!/bin/bash
sum() {
echo "Sum: $(($1 + $2))"
}
sum 10 20
sum 5 15
sum() { ... }
: Defines a function namedsum
.echo "Sum: $(($1 + $2))"
: Calculates and prints the sum of the two arguments.sum 10 20
andsum 5 15
: Calls thesum
function with different arguments.
Example 3: Factorial Function
#!/bin/bash
factorial() {
if [ $1 -le 1 ]; then
echo 1
else
echo $(($1 * $(factorial $(($1 - 1)))))
fi
}
echo "Factorial of 5 is $(factorial 5)"
factorial() { ... }
: Defines a recursive function to calculate the factorial of a number.echo $(($1 * $(factorial $(($1 - 1)))))
: Recursive call to calculate the factorial.echo "Factorial of 5 is $(factorial 5)"
: Prints the factorial of 5.
File Operations
Shell scripts can also perform file operations like creating, reading, and deleting files.
Example 1: Creating and Writing to a File
#!/bin/bash
file="sample.txt"
echo "This is a sample file." > $file
echo "File created and written successfully."
file="sample.txt"
: Assigns the filename to the variablefile
.echo "This is a sample file." > $file
: Writes the text tosample.txt
.>
: Overwrites the file if it exists. Use>>
to append to the file.
Example 2: Reading a File
#!/bin/bash
file="sample.txt"
if [ -f $file ]; then
cat $file
else
echo "File does not exist."
fi
if [ -f $file ]; then ... fi
: Checks ifsample.txt
exists.cat $file
: Displays the contents of the file.
Example 3: Deleting a File
#!/bin/bash
file="sample.txt"
if [ -f $file ]; then
rm $file
echo "File deleted."
else
echo "File does not exist."
fi
if [ -f $file ]; then ... fi
: Checks ifsample.txt
exists.rm $file
: Deletes the file.echo "File deleted."
: Prints a
message indicating the file was deleted.
Conclusion
This tutorial covers the basics of shell scripting. With practice, you can create more complex scripts to automate tasks and manage your system effectively. Happy scripting!
Feel free to modify and expand on these examples to suit your needs. Shell scripting is a versatile skill that can save you time and effort in managing your systems.