Shell Scripting Basics: A Tutorial for Beginners

In this Shell-Scripting course, we will be using a Linux environment to execute our scripts. Linux is a powerful operating system widely used in various fields, from software development to system administration. For the purposes of this course, we will run Linux on a virtual machine using VirtualBox.
VirtualBox is an open-source virtualization tool that allows you to run multiple operating systems simultaneously on your computer. By using VirtualBox, we can create a virtual environment for Linux without affecting the host operating system. You can download and install VirtualBox from the official website. Once VirtualBox is installed, you can create a new virtual machine and install your preferred Linux distribution. Common choices include Ubuntu, CentOS, and Debian. Detailed instructions for setting up a Linux VM can be found in the course resources.
For writing and editing our shell scripts, we will use Visual Studio Code (VS Code), a versatile and powerful code editor that supports a wide range of programming languages and tools. Visual Studio Code, developed by Microsoft, is a free and open-source code editor that provides a rich set of features to enhance your coding experience. Download and install Visual Studio Code from the official website.
Our workflow will involve launching the virtual machine, connecting to the VM using Visual Studio Code, creating and editing shell scripts in Visual Studio Code, and running the scripts directly in the Linux terminal within the VM. This setup ensures a consistent and isolated workspace for developing and testing shell scripts, providing a practical experience of working in a real-world development environment.
So let's dive into this course
PART-1
In this part, we will write a simple bash script and understand some basic concepts of shell scripting.
#! /usr/bin/bash
# this is a comment
echo "Hello World"
echo Our shell name is $BASH
echo Our shell version is $BASH_VERSION
echo Our home directory is $HOME
echo Our current working directory is $PWD
name=Mukunda
age=15
echo The name is $name
echo The age of $name is $age
Explanation:
Shebang (
#! /usr/bin/bash):- This line specifies the interpreter that will be used to execute the script. In this case,
/usr/bin/bashindicates that the Bash shell will be used.
- This line specifies the interpreter that will be used to execute the script. In this case,
Comments (
# this is a comment):- Any line starting with
#is a comment and is not executed. Comments are used to add notes and explanations within the script.
- Any line starting with
echo "Hello World":echois a command used to print text to the terminal. This line prints "Hello World".
Printing Shell Information:
echo Our shell name is $BASH: Prints the name of the shell.echo Our shell version is $BASH_VERSION: Prints the version of the shell.echo Our home directory is $HOME: Prints the home directory path.echo Our current working directory is $PWD: Prints the current working directory path.
Variables:
name=Mukunda: Assigns the value "Mukunda" to the variablename.age=15: Assigns the value 15 to the variableage.echo The name is $name: Prints the value of the variablename.echo The age of $name is $age: Prints the value of the variableage.
This simple script introduces you to the basic concepts of shell scripting, such as using comments, printing output, accessing system variables, and defining and using your own variables.
PART-2
In this part, we will learn how to read and handle user input in a bash script.
#! /usr/bin/bash
# echo 'Enter name: '
# read name
# echo "Entered name : $name"
# read name1 name2 name3
# echo "Names : $name1, $name2, $name3"
# read -p 'username : ' user_var
# read -sp 'password : ' pass_var
# echo
# echo "username : $user_var"
# echo "password : $pass_var"
# echo "Enter name : "
# read
# echo "Name : $REPLY"
# echo "Enter names : "
# read -a names
# echo "Names are : ${names[0]}, ${names[1]}"
Explanation:
Reading a Single Value:
echo 'Enter name: ': Prompts the user to enter their name.read name: Reads the input from the user and stores it in the variablename.echo "Entered name : $name": Prints the value of the variablename.
Reading Multiple Values:
read name1 name2 name3: Reads three inputs from the user and stores them inname1,name2, andname3.echo "Names : $name1, $name2, $name3": Prints the values of the variablesname1,name2, andname3.
Prompting with
read:read -p 'username : ' user_var: Prompts the user to enter a username and stores it inuser_var.read -sp 'password : ' pass_var: Prompts the user to enter a password silently (without showing the input) and stores it inpass_var.echo: Prints a new line (necessary after a silent input).echo "username : $user_var": Prints the value ofuser_var.echo "password : $pass_var": Prints the value ofpass_var.
Using
REPLYVariable:echo "Enter name : ": Prompts the user to enter a name.read: Reads the input and stores it in the default variableREPLY.echo "Name : $REPLY": Prints the value ofREPLY.
Reading an Array:
echo "Enter names : ": Prompts the user to enter names.read -a names: Reads the inputs into an arraynames.echo "Names are : ${names[0]}, ${names[1]}": Prints the first two elements of thenamesarray.
This part of the script demonstrates how to handle user input, including reading single and multiple values, using prompts, reading silently, using the default REPLY variable, and working with arrays.
PART-3
In this part, we will learn how to handle and use positional parameters and arguments in a bash script.
#! /usr/bin/bash
echo $0 $1 $2 $3 '> echo $1 $2 $3'
args=("$@")
echo ${args[0]} ${args[1]} ${args[2]}
echo $@ # to print all arguments
Explanation:
Positional Parameters:
$0,$1,$2,$3: These are positional parameters.$0contains the name of the script,$1contains the first argument passed to the script,$2contains the second argument, and so on.echo $0 $1 $2 $3 '> echo $1 $2 $3': This line prints the script name and the first three arguments passed to the script, followed by a literal string'> echo $1 $2 $3'.
Storing Arguments in an Array:
args=("$@"): This line stores all the arguments passed to the script into an array namedargs. The special variable$@represents all the arguments passed to the script.
Accessing Array Elements:
echo ${args[0]} ${args[1]} ${args[2]}: This line prints the first three elements of theargsarray.
Printing All Arguments:
echo $@: This line prints all the arguments passed to the script.
This part of the script demonstrates how to work with positional parameters and arguments, including accessing individual arguments and storing them in an array for further manipulation.
PART-4
In this part, we will learn how to use conditional statements in a bash script to execute code based on certain conditions.
#! /usr/bin/bash
count=10
if [ $count -eq 9 ]
then
echo "Condition is true"
fi
Explanation:
Variable Assignment:
count=10: This line assigns the value10to the variablecount.
Conditional Statement:
if [ $count -eq 9 ]: This line checks if the value ofcountis equal to9. The-eqoperator is used for numerical comparison.then: If the condition[ $count -eq 9 ]evaluates to true, the commands inside thethenblock will be executed.echo "Condition is true": This line will be executed if the condition is true, printing "Condition is true" to the terminal.fi: This marks the end of theifblock.
Note:
In this specific example, the condition is false because count is 10, not 9. Therefore, the echo "Condition is true" statement will not be executed. You can change the value of count or the condition to test different scenarios.
This part of the script demonstrates the basic syntax and usage of if statements in bash scripting, allowing you to control the flow of your script based on conditions.
PART-5
In this part, we will learn how to use file test operators in a bash script to check different properties of files and directories.
#! /usr/bin/bash
echo -e "Enter the name of the file : \c" # -e is used to enable the interpretation of backslash escape characters
read file_name
if [ -e $file_name ]
then
echo "$file_name found"
else
echo "$file_name not found"
fi
# -e is used to check whether a file exists or not
# -f is used to check if the file exists and is a regular file
# -d is used to check for directories
# -b is used to check for block special files
# -c is used to check for character special files
# -s is used to check if a file is empty or not
# -r is used to check if the file has read permission
# -w is used to check if the file has write permission
# -x is used to check if the file has execute permission
Explanation:
Prompt for File Name:
echo -e "Enter the name of the file : \c": Prompts the user to enter the name of a file. The-eoption enables the interpretation of backslash escape characters, and\ckeeps the cursor on the same line after the prompt.
Read User Input:
read file_name: Reads the input from the user and stores it in the variablefile_name.
File Existence Check:
if [ -e $file_name ]: Checks if the file specified byfile_nameexists. The-eflag is used for this check.then echo "$file_name found": If the file exists, it prints that the file was found.else echo "$file_name not found": If the file does not exist, it prints that the file was not found.fi: Marks the end of theifblock.
File Test Operators:
-e: Check if the file exists.-f: Check if the file exists and is a regular file.-d: Check if the file is a directory.-b: Check if the file is a block special file.-c: Check if the file is a character special file.-s: Check if the file is not empty.-r: Check if the file has read permission.-w: Check if the file has write permission.-x: Check if the file has execute permission.
This part of the script demonstrates how to use various file test operators to check the existence and properties of files and directories, enabling you to handle different file-related scenarios in your scripts.
PART-6
In this part, we will learn how to use nested if statements to check file permissions and write data to a file.
#! /usr/bin/bash
echo -e "Enter the name of the file : \c"
read file_name
if [ -f $file_name ]
then
if [ -w $file_name ]
then
echo "Type some text data. To quit press ctrl+d."
cat >> $file_name
else
echo "The file does not have write permissions"
fi
else
echo "$file_name does not exist"
fi
Explanation:
Prompt for File Name:
echo -e "Enter the name of the file : \c": Prompts the user to enter the name of a file. The-eoption enables the interpretation of backslash escape characters, and\ckeeps the cursor on the same line after the prompt.
Read User Input:
read file_name: Reads the input from the user and stores it in the variablefile_name.
File Existence Check:
if [ -f $file_name ]: Checks if the file specified byfile_nameexists and is a regular file. The-fflag is used for this check.
Nested
ifStatement for Write Permission:if [ -w $file_name ]: If the file exists, this nestedifstatement checks if the file has write permission. The-wflag is used for this check.then echo "Type some text data. To quit press ctrl+d.": If the file has write permission, it prompts the user to enter text data. Pressingctrl+dwill signal the end of input.cat >> $file_name: Appends the input data to the file.else echo "The file does not have write permissions": If the file does not have write permission, it prints a message indicating this.
File Does Not Exist:
else echo "$file_name does not exist": If the file does not exist, it prints a message indicating this.
End of
ifBlocks:fi: Marks the end of the innerifblock.fi: Marks the end of the outerifblock.
This part of the script demonstrates how to use nested if statements to perform more complex checks, such as verifying file existence and permissions before allowing the user to write data to the file.
PART-7
In this part, we will learn how to use logical operators in a bash script to combine multiple conditions in an if statement.
#! /usr/bin/bash
age=25
# Using logical AND operator to check if age is greater than 18 and less than 30
if [ "$age" -gt 18 -a "$age" -lt 30 ]
then
echo "valid age"
else
echo "age not valid"
fi
Explanation:
Variable Assignment:
age=25: This line assigns the value25to the variableage.
Logical AND Operator:
if [ "$age" -gt 18 -a "$age" -lt 30 ]: This line checks if the value ofageis greater than18and less than30. The-aoperator is used for logical AND.
Condition Evaluation:
then echo "valid age": If both conditions are true, this line prints "valid age".else echo "age not valid": If either of the conditions is false, this line prints "age not valid".fi: Marks the end of theifblock
Alternative Using Double Brackets and Logical Operators (&& and ||):
You can also use double brackets with the && (AND) and || (OR) operators for more complex conditions and better readability.
#! /usr/bin/bash
age=25
if [[ "$age" -gt 18 && "$age" -lt 30 ]]
then
echo "valid age"
else
echo "age not valid"
fi
Explanation of Alternative:
Using Double Brackets and
&&Operator:if [[ "$age" -gt 18 && "$age" -lt 30 ]]: This line checks if the value ofageis greater than18and less than30using double brackets and the&&operator.
Condition Evaluation:
then echo "valid age": If both conditions are true, this line prints "valid age".else echo "age not valid": If either of the conditions is false, this line prints "age not valid".fi: Marks the end of theifblock.
This part of the script demonstrates how to use logical operators to combine multiple conditions in an if statement, allowing for more complex decision-making in your scripts.
PART-8
In this part, we will learn how to use logical OR operators in a bash script to combine multiple conditions in an if statement.
#! /usr/bin/bash
age=50
# Using logical OR operator to check if age is equal to 18 or equal to 30
if [ "$age" -eq 18 -o "$age" -eq 30 ]
then
echo "valid age"
else
echo "age not valid"
fi
Explanation:
Variable Assignment:
age=50: This line assigns the value50to the variableage.
Logical OR Operator:
if [ "$age" -eq 18 -o "$age" -eq 30 ]: This line checks if the value ofageis either equal to18or equal to30. The-ooperator is used for logical OR.
Condition Evaluation:
then echo "valid age": If either of the conditions is true, this line prints "valid age".else echo "age not valid": If both conditions are false, this line prints "age not valid".fi: Marks the end of theifblock.
Alternative Using Double Brackets and Logical OR Operator (||):
You can also use double brackets with the || (OR) operator for more complex conditions and better readability.
#! /usr/bin/bash
age=50
if [[ "$age" -eq 18 || "$age" -eq 30 ]] #or,if [ "$age" -gt 18 ] || [ "$age" -lt 30 ]
then
echo "valid age"
else
echo "age not valid"
fi
Explanation of Alternative:
Using Double Brackets and
||Operator:if [[ "$age" -eq 18 || "$age" -eq 30 ]]: This line checks if the value ofageis either equal to18or equal to30using double brackets and the||operator.
Condition Evaluation:
then echo "valid age": If either of the conditions is true, this line prints "valid age".else echo "age not valid": If both conditions are false, this line prints "age not valid".fi: Marks the end of theifblock.
This part of the script demonstrates how to use logical OR operators to combine multiple conditions in an if statement, allowing for more flexible decision-making in your scripts.
PART-9
In this part, we will learn how to perform basic arithmetic operations in a bash script.
#! /usr/bin/bash
num1=20
num2=5
# Using double parentheses for arithmetic operations
echo $(( num1 + num2 ))
echo $(( num1 - num2 ))
echo $(( num1 * num2 ))
echo $(( num1 / num2 ))
Explanation:
Variable Assignment:
num1=20: This line assigns the value20to the variablenum1.num2=5: This line assigns the value5to the variablenum2.
Arithmetic Operations Using Double Parentheses:
echo $(( num1 + num2 )): This line calculates the sum ofnum1andnum2and prints the result (25).echo $(( num1 - num2 )): This line calculates the difference betweennum1andnum2and prints the result (15).echo $(( num1 * num2 )): This line calculates the product ofnum1andnum2and prints the result (100).echo $(( num1 / num2 )): This line calculates the quotient ofnum1divided bynum2and prints the result (4).
#! /usr/bin/bash
num1=20
num2=5
# Using expr command for arithmetic operations
echo $(expr $num1 + $num2)
echo $(expr $num1 - $num2)
echo $(expr $num1 \* $num2)
echo $(expr $num1 / $num2)
Explanation:
Arithmetic Operations Using
exprCommand:The
exprcommand can also be used for arithmetic operations, but it requires escaping the multiplication operator (\*). These lines are commented out but can be used as an alternative to double parentheses.# echo $(expr $num1 + $num2): Calculates the sum.# echo $(expr $num1 - $num2): Calculates the difference.# echo $(expr $num1 \* $num2): Calculates the product (note the escaped\*).# echo $(expr $num1 / $num2): Calculates the quotient.
This part of the script demonstrates how to perform basic arithmetic operations in bash using double parentheses and the expr command, providing flexibility in handling numerical calculations in your scripts.
PART-10
In this part, we will learn how to use the bc command to perform arithmetic operations with floating-point numbers in a bash script.
#! /usr/bin/bash
num1=20.5
num2=5
# Performing arithmetic operations with floating-point numbers using bc
echo "20.5 + 5" | bc
echo "$num1 + $num2" | bc
echo "20.5 - 5" | bc
echo "$num1 - $num2" | bc
echo "20.5 * 5" | bc
echo "$num1 * $num2" | bc
echo "20.5 / 5" | bc
echo "$num1 / $num2" | bc
echo "scale=2; 20.5 / 5" | bc
echo "$num1 % $num2" | bc
# Calculating square root and power using bc
num=27
echo "scale=2; sqrt($num)" | bc -l
echo "scale=20; 3^3" | bc -l
Explanation:
Variable Assignment:
num1=20.5: This line assigns the value20.5to the variablenum1.num2=5: This line assigns the value5to the variablenum2.
Arithmetic Operations Using
bc:echo "20.5 + 5" | bc: This line calculates the sum of20.5and5usingbc.echo "$num1 + $num2" | bc: This line calculates the sum ofnum1andnum2usingbc.echo "20.5 - 5" | bc: This line calculates the difference between20.5and5usingbc.echo "$num1 - $num2" | bc: This line calculates the difference betweennum1andnum2usingbc.echo "20.5 * 5" | bc: This line calculates the product of20.5and5usingbc.echo "$num1 * $num2" | bc: This line calculates the product ofnum1andnum2usingbc.echo "20.5 / 5" | bc: This line calculates the quotient of20.5divided by5usingbc.echo "$num1 / $num2" | bc: This line calculates the quotient ofnum1divided bynum2usingbc.echo "scale=2; 20.5 / 5" | bc: This line calculates the quotient of20.5divided by5usingbcwith thescaleset to2to limit the result to 2 decimal places.echo "$num1 % $num2" | bc: This line calculates the remainder ofnum1divided bynum2usingbc.
Square Root and Power Calculations Using
bc:num=27: This line assigns the value27to the variablenum.echo "scale=2; sqrt($num)" | bc -l: This line calculates the square root ofnumusingbcwith thescaleset to2and the-l(math library) option.echo "scale=20; 3^3" | bc -l: This line calculates3raised to the power of3usingbcwith thescaleset to20for higher precision and the-loption.
This part of the script demonstrates how to use the bc command to perform arithmetic operations with floating-point numbers and perform more complex calculations like square roots and powers in your scripts.
PART-11
In this part, we will learn how to use the case statement in a bash script to handle multiple conditions based on the input argument.
#! /usr/bin/bash
vehicle=$1
case $vehicle in
"car" )
echo "Rent of $vehicle is 100 dollars" ;;
"van" )
echo "Rent of $vehicle is 80 dollars" ;;
"bicycle" )
echo "Rent of $vehicle is 5 dollars" ;;
"truck" )
echo "Rent of $vehicle is 150 dollars" ;;
* )
echo "Unknown vehicle" ;;
esac
Explanation:
Variable Assignment:
vehicle=$1: This line assigns the first command-line argument passed to the script to the variablevehicle.
Case Statement:
case $vehicle in: This line starts thecasestatement, which will compare the value ofvehicleagainst the patterns listed."car" ) echo "Rent of $vehicle is 100 dollars" ;;: Ifvehicleis"car", this line prints the rent for a car and ends with;;."van" ) echo "Rent of $vehicle is 80 dollars" ;;: Ifvehicleis"van", this line prints the rent for a van and ends with;;."bicycle" ) echo "Rent of $vehicle is 5 dollars" ;;: Ifvehicleis"bicycle", this line prints the rent for a bicycle and ends with;;."truck" ) echo "Rent of $vehicle is 150 dollars" ;;: Ifvehicleis"truck", this line prints the rent for a truck and ends with;;.* ) echo "Unknown vehicle" ;;: Ifvehicledoes not match any of the above patterns, this line prints "Unknown vehicle" and ends with;;.esac: This line ends thecasestatement.
This part of the script demonstrates how to use the case statement to handle multiple conditions efficiently, making it easier to manage different possible inputs in your scripts.
PART-12
In this part, we will learn how to use the case statement in a bash script to handle different types of character inputs.
#! /usr/bin/bash
echo -e "Enter some character: \c"
read value
case $value in
[a-z] )
echo "User entered $value, a lowercase letter (a to z)" ;;
[A-Z] )
echo "User entered $value, an uppercase letter (A to Z)" ;;
[0-9] )
echo "User entered $value, a digit (0 to 9)" ;;
? )
echo "User entered $value, a special character" ;;
* )
echo "Unknown input" ;;
esac
Explanation:
Prompting for Input:
echo -e "Enter some character: \c": This line prompts the user to enter a character. The-eoption enables interpretation of backslash escapes, and\ckeeps the cursor on the same line.read value: This line reads the input character and stores it in the variablevalue.
Case Statement:
case $value in: This line starts thecasestatement, which will compare the value ofvalueagainst the patterns listed.[a-z] ) echo "User entered $value, a lowercase letter (a to z)" ;;: Ifvalueis a lowercase letter (a to z), this line prints the corresponding message and ends with;;.[A-Z] ) echo "User entered $value, an uppercase letter (A to Z)" ;;: Ifvalueis an uppercase letter (A to Z), this line prints the corresponding message and ends with;;.[0-9] ) echo "User entered $value, a digit (0 to 9)" ;;: Ifvalueis a digit (0 to 9), this line prints the corresponding message and ends with;;.? ) echo "User entered $value, a special character" ;;: Ifvalueis a special character (anything other than a-z, A-Z, or 0-9), this line prints the corresponding message and ends with;;.* ) echo "Unknown input" ;;: Ifvaluedoes not match any of the above patterns, this line prints "Unknown input" and ends with;;.esac: This line ends thecasestatement.
This part of the script demonstrates how to use the case statement to handle different types of character inputs, allowing for more flexible and robust input handling in your scripts.
PART-13
In this part, we will learn how to work with arrays and strings in a bash script.
#! /usr/bin/bash
# Define an array
os=('ubuntu' 'windows' 'kali')
# Add an element to the array
os[3]='mac'
# Remove an element from the array
unset os[2]
# Print all elements of the array
echo "${os[@]}"
# Print the first element of the array
echo "${os[0]}"
# Print the indices of the array
echo "${!os[@]}"
# Print the length of the array
echo "${#os[@]}"
# Define a string
string=uayegfjhdbfkdsjfhuis
# Print the string
echo "${string[@]}"
# Print the first element of the string
echo "${string[0]}"
# Print the second element of the string (which will be empty since strings don't have elements like arrays)
echo "${string[1]}"
Explanation:
Array Operations:
os=('ubuntu' 'windows' 'kali'): This line defines an array namedoswith three elements: 'ubuntu', 'windows', and 'kali'.os[3]='mac': This line adds a new element 'mac' at the index 3 of the array.unset os[2]: This line removes the element at index 2 ('kali') from the array.echo "${os[@]}": This line prints all elements of the array.echo "${os[0]}": This line prints the first element of the array.echo "${!os[@]}": This line prints the indices of the array.echo "${#os[@]}": This line prints the length (number of elements) of the array.
String Operations:
string=uayegfjhdbfkdsjfhuis: This line defines a string variable namedstring.echo "${string[@]}": This line prints the string. In bash, strings are treated as arrays with a single element.echo "${string[0]}": This line prints the first element of the string, which is the entire string itself.echo "${string[1]}": This line attempts to print the second element of the string, which does not exist, so it will be empty.
This part of the script demonstrates how to perform basic operations with arrays and strings in bash, providing a foundation for more advanced data manipulation in your scripts.
PART-14
In this part, we will learn how to use the while loop in a bash script to iterate through a sequence of numbers.
#! /usr/bin/bash
# while loops
# Initialize a variable
n=1
# While loop to iterate from 1 to 10
while (( $n <= 10 )) # or, one can use --> while [ $n -le 10 ]
do
echo "$n" # Print the current value of n
(( ++n )) # Increment n by 1 using (( ++n )). Other than this you can use these also --> n=$(( n+1 )) and (( n++ ))
done
Explanation:
Initialization:
n=1: This line initializes the variablento1.
While Loop:
while (( $n <= 10 )): This line starts thewhileloop, which continues as long as the value ofnis less than or equal to10.
Loop Body:
echo "$n": This line prints the current value ofn.(( ++n )): This line incrementsnby 1 using the(( ++n ))syntax.
End of Loop:
- The
whileloop continues to executeecho "$n"and(( ++n ))untilnbecomes greater than10.
- The
This will output numbers from 1 to 10, demonstrating how to use a while loop for iterating through a sequence of numbers in bash.
PART-15
In this part, we will use the while loop in a bash script to iterate through numbers and demonstrate opening new terminal windows.
Script 1: Adding Delay
#! /usr/bin/bash
n=1
while [ $n -le 10 ]
do
echo "$n"
(( n++ ))
sleep 2 # Adds a delay of 2 seconds between each iteration
done
Explanation:
Initialization:
n=1: Initializes the variablento1.
While Loop:
while [ $n -le 10 ]: Executes the loop as long asnis less than or equal to10.
Loop Body:
echo "$n": Prints the current value ofn.(( n++ )): Incrementsnby 1 after each iteration.sleep 2: Pauses the script for 2 seconds using thesleepcommand.
End of Loop:
- The loop continues until
nexceeds10.
- The loop continues until
Script 2: Opening New Terminal Windows
#! /usr/bin/bash
n=1
while [ $n -le 10 ]
do
echo "$n"
(( n++ ))
gnome-terminal & # Opens a new terminal window in GNOME desktop environment
done
Explanation:
Initialization:
n=1: Initializes the variablento1.
While Loop:
while [ $n -le 10 ]: Executes the loop as long asnis less than or equal to10.
Loop Body:
echo "$n": Prints the current value ofn.(( n++ )): Incrementsnby 1 after each iteration.gnome-terminal &: Launches a new terminal window in the GNOME desktop environment usinggnome-terminal.
End of Loop:
- The loop continues until
nexceeds10, opening a new terminal window for each iteration.
- The loop continues until
These scripts demonstrate practical uses of while loops in bash for iterating through sequences with delays and performing actions like opening new terminal windows.
PART-16
In this part, we will learn how to use while loops in a bash script to read and process the contents of a file.
#! /usr/bin/bash
# Method 1: Using a pipe to pass the contents of a file to the while loop
cat hello.sh | while read p
do
echo $p
done
# Method 2: Redirecting the file as input to the while loop
while read p
do
echo $p
done < hello.sh
# Method 3: Using IFS (Internal Field Separator) and the -r option to read lines
while IFS= read -r line
do
echo $line
done < /etc/host.conf
Explanation:
Method 1: Using a Pipe
Method 2: Redirecting Input
Method 3: Using IFS and -r Option
while IFS= read -r line; do echo $line; done < /etc/host.conf: This line reads the contents of/etc/host.confline by line usingIFS=(to preserve leading/trailing whitespace) and-r(to prevent backslashes from being interpreted as escape characters). Each line is printed.
This part of the script demonstrates different techniques for reading and processing the contents of a file in bash using while loops.
PART-17
In this part, we will learn how to use the until loop in a bash script to iterate through a sequence of numbers.
#! /usr/bin/bash
# Initialize a variable
n=1
# Until loop to iterate until n is greater than or equal to 10
until [ $n -ge 10 ]
do
echo $n # Print the current value of n
(( n++ )) # Increment n by 1 using (( n++ ))
done
Explanation:
Initialization:
n=1: This line initializes the variablento1.
Until Loop:
until [ $n -ge 10 ]: This line starts theuntilloop, which continues until the value ofnis greater than or equal to10.
Loop Body:
echo $n: This line prints the current value ofn.(( n++ )): This line incrementsnby 1 using the(( n++ ))syntax.
End of Loop:
- The
untilloop continues to executeecho $nand(( n++ ))untilnbecomes greater than or equal to10.
- The
This script demonstrates how to use an until loop for iterating through a sequence of numbers in bash.
PART-18
In this part, we will learn how to use for loops in a bash script to iterate through sequences with different increments and ranges.
Script 1: Simple Range
#! /usr/bin/bash
# For loop with a range from 1 to 7
for i in {1..7} # or,for i in 1 2 3 4 5 6 7
do
echo $i # Print the current value of i
done
Explanation:
For Loop Declaration:
for i in {1..7}: This line starts aforloop that iterates over the sequence of numbers from 1 to 7. The curly braces{1..7}define the range.
Loop Body:
do echo $i: This line is executed for each value in the range.echo $iprints the current value ofi.
End of Loop:
done: This line marks the end of theforloop.
Script 2: Range with Increment
#! /usr/bin/bash
# For loop with a range from 1 to 10, incrementing by 2
for i in {1..10..2} # {START..END..INCREMENT}
do
echo $i # Print the current value of i
done
Explanation:
For Loop Declaration:
for i in {1..10..2}: This line starts aforloop that iterates over the sequence of numbers from 1 to 10, incrementing by 2. The curly braces{1..10..2}define the range and the increment.
Loop Body:
do echo $i: This line is executed for each value in the range.echo $iprints the current value ofi.
End of Loop:
done: This line marks the end of theforloop.
Script 3: C-Style For Loop
#! /usr/bin/bash
# For loop using C-style syntax
for (( i=0; i<5; i++ ))
do
echo $i # Print the current value of i
done
Explanation:
For Loop Declaration:
for (( i=0; i<5; i++ )): This line starts aforloop using C-style syntax, wherei=0initializes the variableito 0,i<5is the loop condition, andi++incrementsiby 1 after each iteration.
Loop Body:
do echo $i: This line is executed for each value ofi.echo $iprints the current value ofi.
End of Loop:
done: This line marks the end of theforloop.
These scripts demonstrate how to use different types of for loops in bash for iterating through sequences with various ranges and increments. Each method provides a flexible way to control the loop's behavior based on your specific needs.
PART-19
In this part, we will learn how to use for loops in a bash script to execute multiple commands and to iterate over items in a directory to identify files and directories.
Script 1: Executing Commands
#! /usr/bin/bash
# For loop to execute a list of commands
for command in ls pwd date
do
echo "-------------------------------$command-------------------------------"
$command # Execute the command stored in the variable $command
done
Explanation:
For Loop Declaration:
for command in ls pwd date: This line starts aforloop that iterates over the list of commandsls,pwd, anddate.
Loop Body:
echo "-------------------------------$command-------------------------------": This line prints a separator with the current command name for clarity.$command: This line executes the command stored in the variablecommand.
End of Loop:
done: This line marks the end of theforloop.
Script 2: Listing Directories
#! /usr/bin/bash
# For loop to list directories in the current directory
for item in *
do
if [ -d $item ] # Check if the item is a directory
then
echo $item # Print the directory name
fi
done
Explanation:
For Loop Declaration:
for item in *: This line starts aforloop that iterates over all items (*) in the current directory.
Loop Body:
if [ -d $item ]: This line checks if the current item is a directory.then echo $item: This line prints the name of the directory if the condition is true.
End of Loop:
done: This line marks the end of theforloop.
Script 3: Listing Files
#! /usr/bin/bash
# For loop to list files in the current directory
for item in *
do
if [ -f $item ] # Check if the item is a file
then
echo $item # Print the file name
fi
done
Explanation:
For Loop Declaration:
for item in *: This line starts aforloop that iterates over all items (*) in the current directory.
Loop Body:
if [ -f $item ]: This line checks if the current item is a file.then echo $item: This line prints the name of the file if the condition is true.
End of Loop:
done: This line marks the end of theforloop.
These scripts demonstrate how to use for loops in bash to execute multiple commands and to identify and list files and directories in the current directory.
PART-20
In this part, we will learn how to use the select loop in a bash script to create a menu system that allows users to select an option and execute corresponding commands.
Script 1: Basic select Loop
#! /usr/bin/bash
# Using select loop to create a menu
select name in Rama Krishna Hayagriva
do
echo "$name selected"
done
Explanation:
Select Loop Declaration:
select name in Rama Krishna Hayagriva: This line starts aselectloop that creates a menu with optionsRama,Krishna, andHayagriva.
Loop Body:
do echo "$name selected": This line prints the selected name.
End of Loop:
done: This line marks the end of theselectloop.
The select loop will display a numbered menu for the user to choose from. The loop will run indefinitely until interrupted.
Script 2: Select Loop with case Statement
#! /usr/bin/bash
# Using select loop with case statement to handle different selections
select name in Rama Krishna Hayagriva
do
case $name in
Rama)
echo Rama selected
;;
Krishna)
echo Krishna selected
;;
Hayagriva)
echo Hayagriva selected
;;
*)
echo "Error: please provide a number between 1 and 3"
esac
done
Explanation:
Select Loop Declaration:
select name in Rama Krishna Hayagriva: This line starts aselectloop that creates a menu with optionsRama,Krishna, andHayagriva.
Loop Body with
caseStatement:case $name in: This line starts acasestatement to handle different selections.Rama) echo Rama selected ;;: This line prints "Rama selected" if the user choosesRama.Krishna) echo Krishna selected ;;: This line prints "Krishna selected" if the user choosesKrishna.Hayagriva) echo Hayagriva selected ;;: This line prints "Hayagriva selected" if the user choosesHayagriva.*) echo "Error: please provide a number between 1 and 3": This line handles any invalid selections and prompts the user to provide a valid number.
End of Loop:
done: This line marks the end of theselectloop.
The select loop will display a numbered menu and the case statement will handle the user's selection, providing specific output based on the selected option. This script enhances the menu system by adding error handling for invalid selections.
PART-21
In this part, we will learn how to use break and continue statements within for loops in a bash script.
Script 1: Using break Statement
#! /usr/bin/bash
# For loop with break statement
for (( i=1; i<=10; i++ ))
do
if [ $i -gt 5 ] # If i is greater than 5
then
break # Exit the loop
fi
echo "$i" # Print the current value of i
done
Explanation:
For Loop Declaration:
for (( i=1; i<=10; i++ )): This line starts aforloop with initialization (i=1), condition (i<=10), and increment (i++).
Loop Body:
if [ $i -gt 5 ]: This line checks ifiis greater than 5.then break: If the condition is true, this line breaks out of the loop.echo "$i": If the condition is false, this line prints the current value ofi.
End of Loop:
done: This line marks the end of theforloop.
In this script, the loop will iterate from 1 to 10, but it will break out of the loop once i exceeds 5, so only numbers 1 to 5 will be printed.
Script 2: Using continue Statement
#! /usr/bin/bash
# For loop with continue statement
for (( i=1; i<=10; i++ ))
do
if [ $i -eq 3 -o $i -eq 6 ] # If i is equal to 3 or 6
then
continue # Skip the current iteration
fi
echo "$i" # Print the current value of i
done
Explanation:
For Loop Declaration:
for (( i=1; i<=10; i++ )): This line starts aforloop with initialization (i=1), condition (i<=10), and increment (i++).
Loop Body:
if [ $i -eq 3 -o $i -eq 6 ]: This line checks ifiis equal to 3 or 6.then continue: If the condition is true, this line skips the current iteration and moves to the next iteration.echo "$i": If the condition is false, this line prints the current value ofi.
End of Loop:
done: This line marks the end of theforloop.
In this script, the loop will iterate from 1 to 10, but it will skip the iterations where i is 3 or 6, so numbers 3 and 6 will not be printed.
PART-22
In this part, we will learn how to define and use functions in a bash script.
Script 1: Basic Function and Exit Function
#! /usr/bin/bash
# Define a function named Hello
function Hello(){
echo "Hello"
}
# Define a function named quit to exit the script
quit (){
exit
}
# Call the Hello function
Hello
# Print a message
echo "foo"
# Call the quit function to exit the script
quit
Explanation:
Function Definition:
function Hello(){ echo "Hello" }: This defines a function namedHellothat prints "Hello".quit () { exit }: This defines a function namedquitthat exits the script.
Function Calls:
Hello: This line calls theHellofunction, printing "Hello".echo "foo": This line prints "foo".quit: This line calls thequitfunction, exiting the script.
Script 2: Function with Parameters
#! /usr/bin/bash
# Define a function named print that accepts parameters
function print(){
echo $1 $2 $3 # Print the first, second, and third parameters
}
# Define a function named quit to exit the script
quit () {
exit
}
# Call the print function with three arguments
print Hello World Again
# Print a message
echo "foo"
# Call the quit function to exit the script
quit
Explanation:
Function Definition:
function print(){ echo $1 $2 $3 }: This defines a function namedprintthat accepts parameters and prints them.quit () { exit }: This defines a function namedquitthat exits the script.
Function Calls:
print Hello World Again: This line calls theprintfunction with three arguments: "Hello", "World", and "Again". The function prints these arguments.echo "foo": This line prints "foo".quit: This line calls thequitfunction, exiting the script.
These scripts demonstrate how to define functions in bash, how to call them, and how to pass parameters to functions. Functions make the script more modular and easier to maintain.
PART-23
In this part, we will learn how to use local variables within functions in a bash script.
Script: Using Local Variables in Functions
#! /usr/bin/bash
# Define a function named print that uses a local variable
function print(){
local name=$1 # Declare a local variable name and assign it the value of the first argument
echo "The name is $name"
}
# Assign a value to the global variable name
name="Krishna"
echo "The name is $name : Before"
# Call the print function with an argument
print Hayagriva
# Print the value of the global variable name after the function call
echo "The name is $name : After"
Explanation:
Function Definition:
function print(){ local name=$1 echo "The name is $name" }: This defines a function namedprintthat accepts one argument. It declares a local variablenamewithin the function and assigns it the value of the first argument. It then prints the value ofname.
Global Variable:
name="Krishna": This line assigns the value "Krishna" to the global variablename.echo "The name is $name : Before": This line prints the value of the global variablenamebefore the function call.
Function Call:
print Hayagriva: This line calls theprintfunction with the argument "Hayagriva". Inside the function, the local variablenameis assigned the value "Hayagriva" and printed.
Global Variable After Function Call:
echo "The name is $name : After": This line prints the value of the global variablenameafter the function call.
In this script, the use of the local keyword ensures that the variable name inside the print function does not affect the global variable name. This is useful for avoiding conflicts and ensuring that changes to variables within functions do not unintentionally affect other parts of the script.
PART-24
In this part, we will learn how to create a bash script that checks for file existence and provides usage instructions.
Script: Checking File Existence and Providing Usage Instructions
#! /usr/bin/bash
# Function to display usage instructions
usage(){
echo "You need to provide an argument : "
echo "usage : $0 file_name"
}
# Function to check if a file exists
is_file_exist(){
local file="$1"
[[ -f "$file" ]] && return 0 || return 1
}
# Check if no arguments are provided
[[ $# -eq 0 ]] && usage && exit 1
# Check if the provided file exists
if ( is_file_exist "$1" )
then
echo "File found"
else
echo "File not found"
fi
Explanation:
Function Definition:
usage:usage(){ echo "You need to provide an argument : "; echo "usage : $0 file_name" }: This function displays usage instructions, indicating that an argument is required and showing how to use the script.
Function Definition:
is_file_exist:is_file_exist(){ local file="$1"; [[ -f "$file" ]] && return 0 || return 1 }: This function checks if the provided file exists. It takes one argument (file), uses a local variable to store it, and returns 0 if the file exists or 1 if it does not.
Argument Check:
[[ $# -eq 0 ]] && usage && exit 1: This line checks if no arguments are provided ($# -eq 0). If true, it calls theusagefunction and exits the script with status 1.
File Existence Check:
if ( is_file_exist "$1" ): This line calls theis_file_existfunction with the first argument.then echo "File found": If the file exists (function returns 0), this line prints "File found".else echo "File not found": If the file does not exist (function returns 1), this line prints "File not found".
This script ensures that the user provides a file name as an argument and checks if the specified file exists, providing appropriate messages based on the result.
PART-25
In this part, we will learn how to use the readonly command to make variables and functions immutable in a bash script.
Script 1: Making a Variable and Function Read-Only
#! /usr/bin/bash
# Declare a variable and mark it as read-only
var=31
readonly var
# Attempt to change the value of the read-only variable
var=50
echo "var => $var"
# Define a function and mark it as read-only
hello(){
echo "Hello World"
}
readonly -f hello
# Attempt to redefine the read-only function
hello(){
echo "Hello World Again"
}
Explanation:
Variable Declaration and Read-Only:
var=31: This line declares a variablevarand assigns it the value 31.readonly var: This line marks the variablevaras read-only.
Attempt to Modify Read-Only Variable:
var=50: This line attempts to change the value ofvar, which will result in an error becausevaris read-only.echo "var => $var": This line prints the value ofvar, which remains 31.
Function Definition and Read-Only:
hello(){ echo "Hello World" }: This line defines a function namedhellothat prints "Hello World".readonly -f hello: This line marks the functionhelloas read-only.
Attempt to Redefine Read-Only Function:
hello(){ echo "Hello World Again" }: This line attempts to redefine the functionhello, which will result in an error becausehellois read-only.
Script 2: Displaying All Read-Only Variables
#! /usr/bin/bash
readonly
Explanation:
readonly: This command, when used without any arguments, lists all read-only variables in the current shell session.
Script 3: Displaying All Read-Only Variables and Functions
#! /usr/bin/bash
readonly -p
Explanation:
readonly -p: This command displays all read-only variables and functions in the current shell session.
Script 4: Declaring and Marking Functions as Read-Only
#! /usr/bin/bash
# Define a function and mark it as read-only
hello(){
echo "Hello"
}
readonly -f hello
# List all read-only functions
readonly -f
Explanation:
Function Definition and Read-Only:
hello(){ echo "Hello" }: This line defines a function namedhellothat prints "Hello".readonly -f hello: This line marks the functionhelloas read-only.
List All Read-Only Functions:
readonly -f: This command lists all read-only functions in the current shell session.
These scripts demonstrate how to use the readonly command to prevent variables and functions from being modified after their initial declaration. This is useful for ensuring the integrity of critical variables and functions in your scripts.
PART-26
In this part, we will learn how to use the trap command to handle signals and execute commands upon receiving specific signals.
Script 1: Displaying the Process ID
#! /usr/bin/bash
echo "pid is $$"
while (( COUNT < 10 ))
do
sleep 2
(( COUNT++ ))
echo $COUNT
done
exit 0
# run this, to kill this type : kill -9 'process id'(the id is the number after "pid is") in a new terminal
Explanation:
echo "pid is $$": This line prints the process ID of the current shell.The
whileloop runs untilCOUNTis less than 10, incrementsCOUNTby 1 every 2 seconds, and prints the value ofCOUNT.
Script 2: Trap and Execute Command on Exit
#! /usr/bin/bash
trap "echo Exit command is detected" 0
echo "Hello World"
exit 0
Explanation:
trap "echo Exit command is detected" 0: This line sets a trap that echoes "Exit command is detected" when the script exits (signal 0).echo "Hello World": This line prints "Hello World".exit 0: This line exits the script with a status of 0.
Script 3: Trap SIGINT (Interrupt Signal)
#! /usr/bin/bash
trap "echo Exit command is detected" SIGINT
echo "pid is $$"
while (( COUNT < 10 ))
do
sleep 2
(( COUNT++ ))
echo $COUNT
done
exit 0
Explanation:
trap "echo Exit command is detected" SIGINT: This line sets a trap that echoes "Exit command is detected" when the script receives the SIGINT signal (usually from pressing Ctrl+C).
Script 4: Attempt to Trap SIGKILL (Kill Signal)
#! /usr/bin/bash
trap "echo Exit command is detected" SIGKILL
echo "pid is $$"
while (( COUNT < 10 ))
do
sleep 2
(( COUNT++ ))
echo $COUNT
done
exit 0
# run this, to kill this type : kill -9 'process id'(the id is the number after "pid is") in a new terminal
Explanation i:
trap "echo Exit command is detected" SIGKILL: This line attempts to set a trap for the SIGKILL signal. However, SIGKILL cannot be trapped or ignored.
Script 5: Trap Multiple Signals and Clean Up
#! /usr/bin/bash
file=/home/linux/Desktop/test # test is the file which I have created. You can create a different in your own system.
trap "rm -f $file; exit" 0 2 15
echo "pid is $$"
while (( COUNT < 10 ))
do
sleep 2
(( COUNT++ ))
echo $COUNT
done
exit 0
# run this , and to kill type in a new terminal : key -15 'process id'
Explanation:
trap "rm -f $file; exit" 0 2 15: This line sets a trap to remove the file specified by$fileand then exit the script when it receives signals 0 (exit), 2 (SIGINT), or 15 (SIGTERM).
Script 6: Trap Multiple Signals, Clean Up, and Echo Message
#! /usr/bin/bash
file=/home/linux/Desktop/test
trap "rm -f $file && echo file deleted; exit" 0 2 15
echo "pid is $$"
while (( COUNT < 10 ))
do
sleep 2
(( COUNT++ ))
echo $COUNT
done
exit 0
# # run this , and to kill type in a new terminal : key -15 'process id'
Explanation:
trap "rm -f $file && echo file deleted; exit" 0 2 15: This line sets a trap to remove the file specified by$file, echo "file deleted", and then exit the script when it receives signals 0 (exit), 2 (SIGINT), or 15 (SIGTERM).
These scripts demonstrate how to use the trap command to handle various signals and perform cleanup tasks, ensuring that your scripts handle interrupts and terminations gracefully.
PART-27
In this part, we will learn how to use the set command to enable and disable debugging, as well as how to use the trap command for cleanup on receiving specific signals.
Script: Enabling and Disabling Debugging
#! /usr/bin/bash
# Enable debugging
set -x
file=/home/linux/Desktop/test
# Disable debugging
set +x
# Set a trap to clean up on exit or specific signals
trap "rm -f $file && echo file deleted; exit" 0 2 15
echo "pid is $$"
# Loop to demonstrate debugging output
while (( COUNT < 10 ))
do
sleep 2
(( COUNT++ ))
echo $COUNT
done
exit 0
Explanation:
Enable Debugging:
set -x: This command enables debugging mode. In debugging mode, each command and its arguments are printed to the terminal before being executed, which helps you see what the script is doing step-by-step.
Variable Declaration:
file=/home/linux/Desktop/test: This line declares a variablefileand assigns it the path/home/linux/Desktop/test.
Disable Debugging:
set +x: This command disables debugging mode. After this point, commands will not be printed to the terminal before execution.
Setting a Trap:
trap "rm -f $file && echo file deleted; exit" 0 2 15: This line sets a trap to remove the file specified by$file, echo "file deleted", and exit the script when it receives signals 0 (exit), 2 (SIGINT), or 15 (SIGTERM).
Print Process ID:
echo "pid is $$": This line prints the process ID of the current shell.
Loop to Demonstrate Debugging Output:
while (( COUNT < 10 )): This line starts awhileloop that continues as long asCOUNTis less than 10.sleep 2: This line makes the script sleep for 2 seconds in each iteration.(( COUNT++ )): This line incrementsCOUNTby 1.echo $COUNT: This line prints the current value ofCOUNT.
Exit Script:
exit 0: This line exits the script with a status of 0.
This script demonstrates how to enable and disable debugging using the set -x and set +x commands, respectively. It also shows how to use the trap command to perform cleanup tasks when the script exits or receives specific signals.
In this debugging, you have many ways to debug orther than set -x set +x
In the terminal you can write "bash -x ./hello.sh"
And normally in the script writing you can use these ways
#!/usr/bin/bash -x
If you found this guide helpful, please leave a comment below with your thoughts or any questions you may have. Your feedback is greatly appreciated and will help improve future content. Happy scripting!