Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Medium

Advance Bash Scripting Guide

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Nowadays, Bash scripting is one of the most popular scripting languages. It helps the users to work smoothly with the command line interface(CLI). It allows us to automate the tasks and helps to streamline the workflow. 

Advance bash scripting guide

In this article, we will discuss the Advanced Bash scripting guide. Firstly, we will discuss what bash scripting is. Then we will understand how we can write scripts in bash. Before moving forward, let us understand what bash is.

A brief about Bash

Bash is a command-line program, and it is a scripting language. It helps to understand and executes commands that we are typing in it. We can also call it a shell. It stands for Bourne Again Shell. It acts as an interface between the user and the operating system(OS). It helps to make communication between the OS and the user. 

There are several features of using bash:

features of bash
  • We can use conditional statements in bash to put some conditions.
     
  • We can create variables in bash to store the value.
     
  • We can also use the loops in bash so that we can repeat the commands.
     
  • We can execute the commands directly from the shell.
     
  • We can declare and use those functions in bash.
     

We can use the above-mentioned features of bash to automate tasks easily. We can also make decisions easily and also can repeat some actions. 

Now, you must be thinking about how and where to use these features. We can write and use these features in a bash script. Let us understand now what bash scripting is.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is Bash Scripting?

Bash scripting means writing scripts or programs in the Bash Shell. The bash shell is a command line interface that we can use for bash scripting. It is available on Unix-like operating systems such as Linux and macOS. So basically, bash scripts are those files in which we can provide some commands that we want to execute. 

These scripts can help us to save time and can automate tasks easily. We can use the .sh extension to save the bash script.

uses of bash scripting

We can also create custom commands by writing the sequence of commands. We can also use the features of bash, as we discussed above. In bash scripting, we can write scripts to perform several tasks at the same time. We can do file manipulation, system administration, data processing, and more tasks by simply writing commands.

Now, you must be confused here about what to write in the script and how it works. Let us start with variables in bash scripting.

Variables in Bash Scripting

Variables are the most important part of any programming language. If we don't have variables, then how will we store values? So in bash scripting, variables play an important role. Using variables, we can store values, and these values can be a string or an integer. 

Let us see how we declare variables in bash scripting:

nameofninja=”Narayan Mishra”

 

So, if we want to access this value, we can write it like this

echo $nameofninja

 

You will see the output like this

Narayan Mishra

Loops in Bash Scripting

Loops are something that is the most required thing while writing code in any programming language. We can perform the same action using a loop. So in bash scripting, we can use loops to automate repetitive tasks. There are two loops that are supported by bash:

for Loop

A for loop is used to iterate through a range of values or elements that are present in a list. For example,

for indexVariable in someListOfElements; do
#Give some commands
done

while Loop

A while loop continues until a specific condition is not becoming false. For example,

while [specificCondition]
do 
#Give some commands
done

 

Now, you might be thinking about where we can use loops in bash scripting. Let us consider some real-time examples.

Note: If you are not able to access the file, then you can use the chmod command to provide read, write, and execute permission.

We can use loops in the following ways:

1. We can use loops when we want to iterate over the files:

Suppose we want to process all the text files in a folder or directory. So, we have a file in which the content is in uppercase

file in uppercase

Now, we want to convert the content to lowercase. So, we can write the following script:

for file in *.txt
do
#Processing the file
tr '[:upper:]' '[:lower:]' < "$file" > "${file%.txt}_lowercase.txt"
done

 

Now, if we run the script

running the script

We will see the following result

after running the script

2. We can use loops when we want to read data from the files:

Suppose we want to read a list of names of ninjas from the ninja_names.txt file. So, we have a file ninja_names

names of ninjas in text file

Now, we want to wish a happy coding journey to each ninja. So, we can write the following script

while read -r ninjaname
do 
echo "Happy coding journey, $ninjaname"
done < ninja_names.txt

 

Now, if we save and run this script, this will give the following result

running the script

Functions in Bash Scripting

If you don’t want to repeat a code again and again, then functions are something that can save you from writing repetitive code. Functions play a crucial role in any of the programming languages. So in bash scripting, functions are used to group a series of commands together. This thing makes our scripts more efficient and reusable. We can use the function in bash scripting like this:

function functionName(){
#Provide some commands
}

 

We can also write it with the function keyword:

functionName(){
#Provide some commands
}

 

Now, you might be thinking about where we can use functions in bash scripting. Let us consider some real-time examples.

We can use functions in the following ways:

1. We can use the functions for handling the errors:

Suppose we want to create a function that can handle the errors during the file processing. If the file is present, it will do some operation and if not, it will throw an error:

doProcessFile() {
  if [ -e "$1" ]; then
    while read -r ninjaname
    do 
echo "Happy coding journey, $ninjaname"
    done < ninja_names.txt
  else
    echo "Error: File not found - $1"
  fi
}


# Processing the files
doProcessFile "ninja_names.txt"
doProcessFile "cnFile2.txt"

 

If we save and run this script, this will give the following result.

running the script

2. We can use the functions for creating custom commands:

Suppose we want to create a custom command to install and configure the software packages.

installConfig(){
# Installing the package
echo "Installation is going on $1"

# Configuring the package
echo "Configuration is going on $1"
echo "Done.."
}
# Installing and configuring
installConfig "mysql"

 

If we save and run this script, it will give the following result.

running the script

Conditional Statements in Bash Scripting

If you have some specific condition and you want to make decisions, then conditional statements come into the picture. We can use conditional statements to execute the code, which depends on the condition, whether it is true or false. So, in bash scripting, we can use conditional statements such as 

if

This statement is used to execute the command if a condition is true. So, we can write it like this

if someCondition
then
#Provide some command
fi

if-else

This statement is used to execute different commands depending on the condition, whether it is true or false. So, we can write it like this

if someCondition
then
#Provide some command if the someCondition is true
else
#Provide some command if the someCondition is false
fi

elif

This statement is used to execute when you have multiple conditions to check. So, we can write it like this

if someCondition
then
#Provide some command if the someCondition is true
elif someAnotherCondtion
then
#Provide some command if the someAnotherCondition is true
else
#Provide some command if all the conditions are false
fi

 

Now, you might be thinking about where we can use conditional statements in bash scripting. Let us consider some real-time examples.

We can use conditional statements in the following ways:

1. We can use conditional statements to check if a file exists:

Suppose we want to check a file if it is present or not and display the content if it is present.

fileName="ninjas.txt"
if [ -e "$fileName" ]; then
  cat "$fileName"
else
  echo "Sorry! The file is not present: $fileName"
fi

 

If we save and run this script, it will give the following result.

running the script

2. We can use conditional statements to check user enter a valid integer or not:

Suppose we want to check if a user has entered a valid number of not.

read -p "Please enter a valid number: " enteredNumber
if [[ "$enteredNumber" =~ ^[0-9]+$ ]]; then
  echo "It is a valid number: $enteredNumber"
else
  echo "Sorry! It is not a valid number."
fi

 

If we save and run this script, it will give the following result.

running the script

Arrays in Bash Scripting

If we have a similar type of data and we want to store it somewhere, then arrays come to our mind. Arrays are also one of the important concepts that are used in almost programming languages. So in bash, the array is a collection of elements. It can store many values of the same type in a single variable. So, in bash scripting, we can use arrays like this

ninjaNames=("Narayan Mishra " "Alisha Chhabra" "Mehak Goel")


We can also declare an array by using the declare keyword:

declare -a ninjaNames=ninjaNames=("Narayan Mishra " "Alisha Chhabra" "Mehak Goel")


Now, you might be thinking about where we can use arrays in bash scripting. Let us consider some real-time examples.

We can use arrays in the following ways:

1. We can use arrays to store the data sets:

Suppose we want to store the names of the ninjas and the questions solved by them in two lists.

ninjaNames=("Narayan Mishra " "Alisha Chhabra" "Mehak Goel")
questionsSolved=("300" "350" "700" )


# Accessing elements from the arrays
for str in ${ninjaNames[@]}; do
  echo $str
done

 

If we save and run this script, it will give the following output.

Narayan Mishra
Alisha Chhabra
Mehak Goel

2. We can use arrays to process the command line arguments:

Supoose, we want to store the command line arguments and want to process them in a structured manner.

arguments=("$@")
for argumentExample in "${arguments[@]}"; do
  echo "Argument is: $argumentExample"
done

 

If we save and run this script, it will give the following result.

running the script

Frequently Asked Questions

What do you mean by bash scripting?

Bash scripting means writing scripts using the Bash scripting language. For writing bash scripting, we need a Bash shell. It is a command-line interface that is available on Unix-like OS.

What do you understand by advanced bash scripting?

Advanced Bash scripting uses more complex features and techniques in Bash scripting. Using advanced bash scripting, we can write sophisticated and efficient scripts. 

Why do we use regular expressions in advanced bash scripting?

Regular expressions are used in advanced bash scripting for advanced text parsing. We can also use it to search and substitution operations. These types of expressions help us in pattern-matching and facilitating sophisticated data processing.

Why do we use arrays in advanced bash scripting?

Arrays in advance bash scripting enable the storage and manipulation of multiple values within a single variable. They are beneficial for processing structured data efficiently and enable complex data handling tasks.

Conclusion

In this blog, we have discussed about advance bash scripting guide. We have covered some features that are required in advance bash scripting. If you want to learn more about Bash scripting, then you can check out our blogs:

We hope this blog helps you to get knowledge about the advance bash scripting guide. You can refer to our guided paths on the Codestudio platform. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

To practice and improve yourself in the interview, you can also check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews.

Happy Learning!!

Topics covered
1.
Introduction
2.
A brief about Bash
3.
What is Bash Scripting?
4.
Variables in Bash Scripting
5.
Loops in Bash Scripting
5.1.
for Loop
5.2.
while Loop
5.3.
1. We can use loops when we want to iterate over the files:
5.4.
2. We can use loops when we want to read data from the files:
6.
Functions in Bash Scripting
6.1.
1. We can use the functions for handling the errors:
6.2.
2. We can use the functions for creating custom commands:
7.
Conditional Statements in Bash Scripting
7.1.
if
7.2.
if-else
7.3.
elif
7.4.
1. We can use conditional statements to check if a file exists:
7.5.
2. We can use conditional statements to check user enter a valid integer or not:
8.
Arrays in Bash Scripting
8.1.
1. We can use arrays to store the data sets:
8.2.
2. We can use arrays to process the command line arguments:
9.
Frequently Asked Questions
9.1.
What do you mean by bash scripting?
9.2.
What do you understand by advanced bash scripting?
9.3.
Why do we use regular expressions in advanced bash scripting?
9.4.
Why do we use arrays in advanced bash scripting?
10.
Conclusion