Skip to main content

Command Palette

Search for a command to run...

Shell Scripting Basics: A Tutorial for Beginners

Updated
43 min read
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:

  1. Shebang (#! /usr/bin/bash):

    • This line specifies the interpreter that will be used to execute the script. In this case, /usr/bin/bash indicates that the Bash shell will be used.
  2. 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.
  3. echo "Hello World":

    • echo is a command used to print text to the terminal. This line prints "Hello World".
  4. 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.

  5. Variables:

    • name=Mukunda: Assigns the value "Mukunda" to the variable name.

    • age=15: Assigns the value 15 to the variable age.

    • echo The name is $name: Prints the value of the variable name.

    • echo The age of $name is $age: Prints the value of the variable age.

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:

  1. 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 variable name.

    • echo "Entered name : $name": Prints the value of the variable name.

  2. Reading Multiple Values:

    • read name1 name2 name3: Reads three inputs from the user and stores them in name1, name2, and name3.

    • echo "Names : $name1, $name2, $name3": Prints the values of the variables name1, name2, and name3.

  3. Prompting withread:

    • read -p 'username : ' user_var: Prompts the user to enter a username and stores it in user_var.

    • read -sp 'password : ' pass_var: Prompts the user to enter a password silently (without showing the input) and stores it in pass_var.

    • echo: Prints a new line (necessary after a silent input).

    • echo "username : $user_var": Prints the value of user_var.

    • echo "password : $pass_var": Prints the value of pass_var.

  4. Using REPLY Variable:

    • echo "Enter name : ": Prompts the user to enter a name.

    • read: Reads the input and stores it in the default variable REPLY.

    • echo "Name : $REPLY": Prints the value of REPLY.

  5. Reading an Array:

    • echo "Enter names : ": Prompts the user to enter names.

    • read -a names: Reads the inputs into an array names.

    • echo "Names are : ${names[0]}, ${names[1]}": Prints the first two elements of the names array.

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:

  1. Positional Parameters:

    • $0, $1, $2, $3: These are positional parameters. $0 contains the name of the script, $1 contains the first argument passed to the script, $2 contains 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'.

  2. Storing Arguments in an Array:

    • args=("$@"): This line stores all the arguments passed to the script into an array named args. The special variable $@ represents all the arguments passed to the script.
  3. Accessing Array Elements:

    • echo ${args[0]} ${args[1]} ${args[2]}: This line prints the first three elements of the args array.
  4. 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:

  1. Variable Assignment:

    • count=10: This line assigns the value 10 to the variable count.
  2. Conditional Statement:

    • if [ $count -eq 9 ]: This line checks if the value of count is equal to 9. The -eq operator is used for numerical comparison.

    • then: If the condition [ $count -eq 9 ] evaluates to true, the commands inside the then block 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 the if block.

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:

  1. Prompt for File Name:

    • echo -e "Enter the name of the file : \c": Prompts the user to enter the name of a file. The -e option enables the interpretation of backslash escape characters, and \c keeps the cursor on the same line after the prompt.
  2. Read User Input:

    • read file_name: Reads the input from the user and stores it in the variable file_name.
  3. File Existence Check:

    • if [ -e $file_name ]: Checks if the file specified by file_name exists. The -e flag 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 the if block.

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:

  1. Prompt for File Name:

    • echo -e "Enter the name of the file : \c": Prompts the user to enter the name of a file. The -e option enables the interpretation of backslash escape characters, and \c keeps the cursor on the same line after the prompt.
  2. Read User Input:

    • read file_name: Reads the input from the user and stores it in the variable file_name.
  3. File Existence Check:

    • if [ -f $file_name ]: Checks if the file specified by file_name exists and is a regular file. The -f flag is used for this check.
  4. Nestedif Statement for Write Permission:

    • if [ -w $file_name ]: If the file exists, this nested if statement checks if the file has write permission. The -w flag 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. Pressing ctrl+d will 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.

  5. File Does Not Exist:

    • else echo "$file_name does not exist": If the file does not exist, it prints a message indicating this.
  6. End ofif Blocks:

    • fi: Marks the end of the inner if block.

    • fi: Marks the end of the outer if block.

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:

  1. Variable Assignment:

    • age=25: This line assigns the value 25 to the variable age.
  2. Logical AND Operator:

    • if [ "$age" -gt 18 -a "$age" -lt 30 ]: This line checks if the value of age is greater than 18 and less than 30. The -a operator is used for logical AND.
  3. 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 the if block

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:

  1. Using Double Brackets and&& Operator:

    • if [[ "$age" -gt 18 && "$age" -lt 30 ]]: This line checks if the value of age is greater than 18 and less than 30 using double brackets and the && operator.
  2. 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 the if block.

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:

  1. Variable Assignment:

    • age=50: This line assigns the value 50 to the variable age.
  2. Logical OR Operator:

    • if [ "$age" -eq 18 -o "$age" -eq 30 ]: This line checks if the value of age is either equal to 18 or equal to 30. The -o operator is used for logical OR.
  3. 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 the if block.

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:

  1. Using Double Brackets and|| Operator:

    • if [[ "$age" -eq 18 || "$age" -eq 30 ]]: This line checks if the value of age is either equal to 18 or equal to 30 using double brackets and the || operator.
  2. 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 the if block.

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:

  1. Variable Assignment:

    • num1=20: This line assigns the value 20 to the variable num1.

    • num2=5: This line assigns the value 5 to the variable num2.

  2. Arithmetic Operations Using Double Parentheses:

    • echo $(( num1 + num2 )): This line calculates the sum of num1 and num2 and prints the result (25).

    • echo $(( num1 - num2 )): This line calculates the difference between num1 and num2 and prints the result (15).

    • echo $(( num1 * num2 )): This line calculates the product of num1 and num2 and prints the result (100).

    • echo $(( num1 / num2 )): This line calculates the quotient of num1 divided by num2 and 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:

  1. Arithmetic Operations Usingexpr Command:

    • The expr command 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:

  1. Variable Assignment:

    • num1=20.5: This line assigns the value 20.5 to the variable num1.

    • num2=5: This line assigns the value 5 to the variable num2.

  2. Arithmetic Operations Usingbc:

    • echo "20.5 + 5" | bc: This line calculates the sum of 20.5 and 5 using bc.

    • echo "$num1 + $num2" | bc: This line calculates the sum of num1 and num2 using bc.

    • echo "20.5 - 5" | bc: This line calculates the difference between 20.5 and 5 using bc.

    • echo "$num1 - $num2" | bc: This line calculates the difference between num1 and num2 using bc.

    • echo "20.5 * 5" | bc: This line calculates the product of 20.5 and 5 using bc.

    • echo "$num1 * $num2" | bc: This line calculates the product of num1 and num2 using bc.

    • echo "20.5 / 5" | bc: This line calculates the quotient of 20.5 divided by 5 using bc.

    • echo "$num1 / $num2" | bc: This line calculates the quotient of num1 divided by num2 using bc.

    • echo "scale=2; 20.5 / 5" | bc: This line calculates the quotient of 20.5 divided by 5 using bc with the scale set to 2 to limit the result to 2 decimal places.

    • echo "$num1 % $num2" | bc: This line calculates the remainder of num1 divided by num2 using bc.

  3. Square Root and Power Calculations Usingbc:

    • num=27: This line assigns the value 27 to the variable num.

    • echo "scale=2; sqrt($num)" | bc -l: This line calculates the square root of num using bc with the scale set to 2 and the -l (math library) option.

    • echo "scale=20; 3^3" | bc -l: This line calculates 3 raised to the power of 3 using bc with the scale set to 20 for higher precision and the -l option.

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:

  1. Variable Assignment:

    • vehicle=$1: This line assigns the first command-line argument passed to the script to the variable vehicle.
  2. Case Statement:

    • case $vehicle in: This line starts the case statement, which will compare the value of vehicle against the patterns listed.

    • "car" ) echo "Rent of $vehicle is 100 dollars" ;;: If vehicle is "car", this line prints the rent for a car and ends with ;;.

    • "van" ) echo "Rent of $vehicle is 80 dollars" ;;: If vehicle is "van", this line prints the rent for a van and ends with ;;.

    • "bicycle" ) echo "Rent of $vehicle is 5 dollars" ;;: If vehicle is "bicycle", this line prints the rent for a bicycle and ends with ;;.

    • "truck" ) echo "Rent of $vehicle is 150 dollars" ;;: If vehicle is "truck", this line prints the rent for a truck and ends with ;;.

    • * ) echo "Unknown vehicle" ;;: If vehicle does not match any of the above patterns, this line prints "Unknown vehicle" and ends with ;;.

    • esac: This line ends the case statement.

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:

  1. Prompting for Input:

    • echo -e "Enter some character: \c": This line prompts the user to enter a character. The -e option enables interpretation of backslash escapes, and \c keeps the cursor on the same line.

    • read value: This line reads the input character and stores it in the variable value.

  2. Case Statement:

    • case $value in: This line starts the case statement, which will compare the value of value against the patterns listed.

    • [a-z] ) echo "User entered $value, a lowercase letter (a to z)" ;;: If value is 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)" ;;: If value is 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)" ;;: If value is a digit (0 to 9), this line prints the corresponding message and ends with ;;.

    • ? ) echo "User entered $value, a special character" ;;: If value is 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" ;;: If value does not match any of the above patterns, this line prints "Unknown input" and ends with ;;.

    • esac: This line ends the case statement.

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:

  1. Array Operations:

    • os=('ubuntu' 'windows' 'kali'): This line defines an array named os with 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.

  2. String Operations:

    • string=uayegfjhdbfkdsjfhuis: This line defines a string variable named string.

    • 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:

  1. Initialization:

    • n=1: This line initializes the variable n to 1.
  2. While Loop:

    • while (( $n <= 10 )): This line starts the while loop, which continues as long as the value of n is less than or equal to 10.
  3. Loop Body:

    • echo "$n": This line prints the current value of n.

    • (( ++n )): This line increments n by 1 using the (( ++n )) syntax.

  4. End of Loop:

    • The while loop continues to execute echo "$n" and (( ++n )) until n becomes greater than 10.

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:

  1. Initialization:

    • n=1: Initializes the variable n to 1.
  2. While Loop:

    • while [ $n -le 10 ]: Executes the loop as long as n is less than or equal to 10.
  3. Loop Body:

    • echo "$n": Prints the current value of n.

    • (( n++ )): Increments n by 1 after each iteration.

    • sleep 2: Pauses the script for 2 seconds using the sleep command.

  4. End of Loop:

    • The loop continues until n exceeds 10.

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:

  1. Initialization:

    • n=1: Initializes the variable n to 1.
  2. While Loop:

    • while [ $n -le 10 ]: Executes the loop as long as n is less than or equal to 10.
  3. Loop Body:

    • echo "$n": Prints the current value of n.

    • (( n++ )): Increments n by 1 after each iteration.

    • gnome-terminal &: Launches a new terminal window in the GNOME desktop environment using gnome-terminal.

  4. End of Loop:

    • The loop continues until n exceeds 10, opening a new terminal window for each iteration.

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:

  1. Method 1: Using a Pipe

    • cathello.sh| while read p: This line uses cat to read the contents of hello.sh and pipes it to the while loop.

    • do echo $p: This line prints each line of the file.

    • done: Ends the while loop.

  2. Method 2: Redirecting Input

    • while read p; do echo $p; done <hello.sh: This line redirects the contents of hello.sh as input to the while loop, which reads and prints each line.
  3. 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.conf line by line using IFS= (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:

  1. Initialization:

    • n=1: This line initializes the variable n to 1.
  2. Until Loop:

    • until [ $n -ge 10 ]: This line starts the until loop, which continues until the value of n is greater than or equal to 10.
  3. Loop Body:

    • echo $n: This line prints the current value of n.

    • (( n++ )): This line increments n by 1 using the (( n++ )) syntax.

  4. End of Loop:

    • The until loop continues to execute echo $n and (( n++ )) until n becomes greater than or equal to 10.

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:

  1. For Loop Declaration:

    • for i in {1..7}: This line starts a for loop that iterates over the sequence of numbers from 1 to 7. The curly braces {1..7} define the range.
  2. Loop Body:

    • do echo $i: This line is executed for each value in the range. echo $i prints the current value of i.
  3. End of Loop:

    • done: This line marks the end of the for loop.

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:

  1. For Loop Declaration:

    • for i in {1..10..2}: This line starts a for loop 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.
  2. Loop Body:

    • do echo $i: This line is executed for each value in the range. echo $i prints the current value of i.
  3. End of Loop:

    • done: This line marks the end of the for loop.

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:

  1. For Loop Declaration:

    • for (( i=0; i<5; i++ )): This line starts a for loop using C-style syntax, where i=0 initializes the variable i to 0, i<5 is the loop condition, and i++ increments i by 1 after each iteration.
  2. Loop Body:

    • do echo $i: This line is executed for each value of i. echo $i prints the current value of i.
  3. End of Loop:

    • done: This line marks the end of the for loop.

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:

  1. For Loop Declaration:

    • for command in ls pwd date: This line starts a for loop that iterates over the list of commands ls, pwd, and date.
  2. 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 variable command.

  3. End of Loop:

    • done: This line marks the end of the for loop.

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:

  1. For Loop Declaration:

    • for item in *: This line starts a for loop that iterates over all items (*) in the current directory.
  2. 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.

  3. End of Loop:

    • done: This line marks the end of the for loop.

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:

  1. For Loop Declaration:

    • for item in *: This line starts a for loop that iterates over all items (*) in the current directory.
  2. 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.

  3. End of Loop:

    • done: This line marks the end of the for loop.

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:

  1. Select Loop Declaration:

    • select name in Rama Krishna Hayagriva: This line starts a select loop that creates a menu with options Rama, Krishna, and Hayagriva.
  2. Loop Body:

    • do echo "$name selected": This line prints the selected name.
  3. End of Loop:

    • done: This line marks the end of the select loop.

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:

  1. Select Loop Declaration:

    • select name in Rama Krishna Hayagriva: This line starts a select loop that creates a menu with options Rama, Krishna, and Hayagriva.
  2. Loop Body withcase Statement:

    • case $name in: This line starts a case statement to handle different selections.

    • Rama) echo Rama selected ;;: This line prints "Rama selected" if the user chooses Rama.

    • Krishna) echo Krishna selected ;;: This line prints "Krishna selected" if the user chooses Krishna.

    • Hayagriva) echo Hayagriva selected ;;: This line prints "Hayagriva selected" if the user chooses Hayagriva.

    • *) 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.

  3. End of Loop:

    • done: This line marks the end of the select loop.

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:

  1. For Loop Declaration:

    • for (( i=1; i<=10; i++ )): This line starts a for loop with initialization (i=1), condition (i<=10), and increment (i++).
  2. Loop Body:

    • if [ $i -gt 5 ]: This line checks if i is 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 of i.

  3. End of Loop:

    • done: This line marks the end of the for loop.

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:

  1. For Loop Declaration:

    • for (( i=1; i<=10; i++ )): This line starts a for loop with initialization (i=1), condition (i<=10), and increment (i++).
  2. Loop Body:

    • if [ $i -eq 3 -o $i -eq 6 ]: This line checks if i is 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 of i.

  3. End of Loop:

    • done: This line marks the end of the for loop.

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:

  1. Function Definition:

    • function Hello(){ echo "Hello" }: This defines a function named Hello that prints "Hello".

    • quit () { exit }: This defines a function named quit that exits the script.

  2. Function Calls:

    • Hello: This line calls the Hello function, printing "Hello".

    • echo "foo": This line prints "foo".

    • quit: This line calls the quit function, 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:

  1. Function Definition:

    • function print(){ echo $1 $2 $3 }: This defines a function named print that accepts parameters and prints them.

    • quit () { exit }: This defines a function named quit that exits the script.

  2. Function Calls:

    • print Hello World Again: This line calls the print function with three arguments: "Hello", "World", and "Again". The function prints these arguments.

    • echo "foo": This line prints "foo".

    • quit: This line calls the quit function, 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:

  1. Function Definition:

    • function print(){ local name=$1 echo "The name is $name" }: This defines a function named print that accepts one argument. It declares a local variable name within the function and assigns it the value of the first argument. It then prints the value of name.
  2. Global Variable:

    • name="Krishna": This line assigns the value "Krishna" to the global variable name.

    • echo "The name is $name : Before": This line prints the value of the global variable name before the function call.

  3. Function Call:

    • print Hayagriva: This line calls the print function with the argument "Hayagriva". Inside the function, the local variable name is assigned the value "Hayagriva" and printed.
  4. Global Variable After Function Call:

    • echo "The name is $name : After": This line prints the value of the global variable name after 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:

  1. 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.
  2. 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.
  3. Argument Check:

    • [[ $# -eq 0 ]] && usage && exit 1: This line checks if no arguments are provided ($# -eq 0). If true, it calls the usage function and exits the script with status 1.
  4. File Existence Check:

    • if ( is_file_exist "$1" ): This line calls the is_file_exist function 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:

  1. Variable Declaration and Read-Only:

    • var=31: This line declares a variable var and assigns it the value 31.

    • readonly var: This line marks the variable var as read-only.

  2. Attempt to Modify Read-Only Variable:

    • var=50: This line attempts to change the value of var, which will result in an error because var is read-only.

    • echo "var => $var": This line prints the value of var, which remains 31.

  3. Function Definition and Read-Only:

    • hello(){ echo "Hello World" }: This line defines a function named hello that prints "Hello World".

    • readonly -f hello: This line marks the function hello as read-only.

  4. Attempt to Redefine Read-Only Function:

    • hello(){ echo "Hello World Again" }: This line attempts to redefine the function hello, which will result in an error because hello is 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:

  1. Function Definition and Read-Only:

    • hello(){ echo "Hello" }: This line defines a function named hello that prints "Hello".

    • readonly -f hello: This line marks the function hello as read-only.

  2. 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 while loop runs until COUNT is less than 10, increments COUNT by 1 every 2 seconds, and prints the value of COUNT.

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 $file and 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:

  1. 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.
  2. Variable Declaration:

    • file=/home/linux/Desktop/test: This line declares a variable file and assigns it the path /home/linux/Desktop/test.
  3. Disable Debugging:

    • set +x: This command disables debugging mode. After this point, commands will not be printed to the terminal before execution.
  4. 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).
  5. Print Process ID:

    • echo "pid is $$": This line prints the process ID of the current shell.
  6. Loop to Demonstrate Debugging Output:

    • while (( COUNT < 10 )): This line starts a while loop that continues as long as COUNT is less than 10.

    • sleep 2: This line makes the script sleep for 2 seconds in each iteration.

    • (( COUNT++ )): This line increments COUNT by 1.

    • echo $COUNT: This line prints the current value of COUNT.

  7. 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

  1. In the terminal you can write "bash -x ./hello.sh"

    And normally in the script writing you can use these ways

  2. #!/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!

More from this blog

Arijit's blog

19 posts

Welcome to my tech blog! If you love tech and insightful articles, you're in the right place. I regularly post deep dives into various topics. Stay connected and enjoy the content. Thank you!