Open In App

Bash Scripting – Introduction to Bash and Bash Scripting

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Bash is a command-line interpreter or Unix Shell and it is widely used in GNU/Linux Operating System.  It is written by Brian Jhan Fox. It is used as a default login shell for most Linux distributions. Scripting is used to automate the execution of the tasks so that humans do not need to perform them individually. Bash scripting is a great way to automate different types of tasks in a system. Developers can avoid doing repetitive tasks using bash scripting. 

Bash scripting supports variables, conditional statements, and loops just like programming languages. Below are some of the applications of Bash Scripts – 

Applications of Bash Scripts:

  • Manipulating files
  • Executing routine tasks like Backup operation
  • Automation

The advantages of using Bash Scripts are given below –

Advantages of Bash Scripts:

  • It is simple.
  • It helps to avoid doing repetitive tasks
  • Easy to use
  • Frequently performed tasks can be automated
  • A sequence of commands can be run as a single command.

The disadvantages of the Bash Scripts are given below – 

Disadvantages of Bash Scripts:

  • Any mistake while writing can be costly.
  • A new process launched for almost every shell command executed
  • Slow execution speed 
  • Compatibility problems between different platforms

How to Write Bash Scripts?

To write a Bash Script we will follow the steps –

  • First, we will create a file with the .sh extension.
  • Next, we will write down the bash scripts within it
  • After that, we will provide execution permission to it.

To create and write a file with the .sh extension we can use gedit text editor. The command for it will be –

gedit scriptname.sh

The first line of our script file will be –

#!/bin/bash

This will tell, the system to use Bash for execution. Then we can write our own scripts.

Let’s write down just a simple script that will print some lines in the terminal. The code for it will be –

#!/bin/bash         

echo "Hello, GeeksforGeeks"

Now we will save the file and provide the execution permission to it. To do so use the following command –

chmod +x scriptname.sh

Next to execute the following script we will use the following command –

./scriptname.sh

Here is the terminal shell pictorial depiction after executing the above commands as follows:  

 

Here the script file name is gfg.sh.

Now we can also write more complicated commands using Bash Scripts. Here is an example below in which we are using a condition statement –

Example Script:

#!/bin/bash         
Age=17
if [ "$Age" -ge 18 ]; then
    echo "You can vote"
else
    echo "You cannot vote"    
fi

Output:

You cannot vote

Here is the terminal shell pictorial depiction after executing the above script as follows:  

 

In the above way, we can execute multiple Bash commands all at once.

Now Let’s look into the other important concepts related to Bash Scripting.

File Names and Permissions

In the above example, we have saved the file using gfg.sh name and also provided execute permission using chmod command. Now, let’s understand why we have done that. 

While writing bash scripts we should save our file with the .sh extension, so that the Linux system can execute it. When we first create a file with the .sh extension, it doesn’t have any execute permission and without the execute permission the script will not work. So, we should provide execute permission to it using the chmod command. 

The filename of a bash script can be anything but by convention, it is recommended to use snake case ( my_bash_script.sh ) or hyphens ( my-bash-script.sh ) for naming a script file.

Variables

We can use variables in bash scripting. Below is a sample program to understand the usage of variables in Bash scripts.

Example Script:

Name="SATYAJIT GHOSH"
Age=20

echo "The name is $Name and Age is $Age"

Output of Variables:

The name is SATYAJIT GHOSH and Age is 20

So, here is have declared two variables Name and another one is Age. These variables are accessible using $Name and $Age. That means, we can declare a variable in a bash script using VariableName=Value and can access it using $VariableName. Here is the terminal shell pictorial depiction after executing the above script as follows:  

 

There are two types of variables present within Bash Scripting. Conventionally, If a variable, is declared inside a function then it is generally a local variable and if it is declared outside then it is a global variable. In the case of a bash script, this concept is a little bit different, here any variable whether it is written inside a function or outside a function by default is a global variable. If we want to make a local variable then we need to use the keyword “local”.

Note: It is best practice to always use a local variable inside a function to avoid any unnecessary confusion.  

An example of the same is given below –

Example Script:

#!/bin/bash

var1="Apple" #global variable
myfun(){
    local var2="Banana" #local variable
    var3="Cherry" #global variable
    echo "The name of first fruit is $var1"
    echo "The name of second fruit is $var2"
}
myfun #calling function

echo "The name of first fruit is $var1"
#trying to access local variable
echo "The name of second fruit is $var2"
echo "The name of third fruit is $var3"

Output of local and global variables:

The name of first fruit is Apple
The name of second fruit is Banana
The name of first fruit is Apple
The name of second fruit is 
The name of third fruit is Cherry

Here in this above example, var2 is a local variable, so when we are accessing it from the function it is doing fine but when we are trying to access it outside the function, it is giving us an empty result in the output.

On the other hand, unlike programming languages, even though var3 is defined inside a function still it is acting as a global variable and it can be accessed outside the function. Below is the terminal shell depiction after executing the script –

 

Input and Output

Input & output are fundamental concepts for shell scripting. A script can take one or more inputs and can also produce zero or many outputs. It may even produce some errors.  Let’s understand this with an example –

Example Script:

echo "Enter filename"
read filename

if [ -e $filename ]
then
echo "$filename is exits on the directory"
cat $filename

else
    cat > $filename
    echo "File created"
fi

Output of Input & Output:

First time:

Enter filename
geeks.txt
Hello Geek
File created

Second time:

Enter filename
geeks.txt
geeks.txt is exits on the directory
Hello Geek

So, in this above example the first time, the script could not find any file with that file name, and the else block gets executed. It created the file and put some data into that file. When we run it a second time with the same file name, then it finds the file. So, is the if block gets executed and that displays the contents of the file.  Reading the file contents is input and on the first time putting data into the file is considered to be output. Here we have used > for storing the content in a file.  The > notation is used to redirect stdout to a file. On the other hand, we can use  2> notation to redirect stderr, and &>  to redirect both stdout and stderr.

Below is the terminal shell pictorial depiction after executing the following script – 

 

Functions

In programming, A function is a block of code that performs some tasks and it can be called multiple times for performing tasks. The simplest example of the use of function in Bash scripting can be given as –

Example Script:

#!/bin/bash
#It is a function
myFunction () {
echo Hello World from GeeksforGeeks
}

#function call
myFunction 

Output of Functions:

Hello World from GeeksforGeeks

The above example shows a function that prints something when called.

So, the basic syntax for writing functions within a Bash Script will be –

Syntax of Functions:

#for defining
function_name(){
    commands
    .....
}

function_name # for calling

Besides this, we can also have functions with passing arguments and with return values.

Decision Making

In programming, Decision Making is one of the important concepts. The programmer provides one or more conditions for the execution of a block of code. If the conditions are satisfied then those block of codes only gets executed.

Two types of decision-making statements are used within shell scripting. They are –

1. If-else statement:

If else statement is a conditional statement. It can be used to execute two different codes based on whether the given condition is satisfied or not.

There are a couple of varieties present within the if-else statement. They are –

  • if-fi 
  • if-else-fi 
  • if-elif-else-fi 
  • nested if-else

The syntax for the simplest one will be –

Syntax of If-else statement:

if [ expression ]; then

    statements

fi

Example Script:

Name="Satyajit"
if [ "$Name" = "Satyajit" ]; then
  echo "His name is Satyajit. It is true."
fi

Output of if-else statement:

His name is Satyajit. It is true.

In the above example, during the condition checking the name matches and the condition becomes true. Hence, the block of code present within the if block gets executed. In case the name doesn’t match then will not have an output. Below is the terminal shell pictorial depiction after executing the following script – 

 

2. case-sac statement:

case-sac is basically working the same as switch statement in programming. Sometimes if we have to check multiple conditions, then it may get complicated using if statements. At those moments we can use a case-sac statement. The syntax will be –

Syntax of case-sac statement:

case $var in
   Pattern 1) Statement 1;;
   Pattern n) Statement n;;
esac

Example Script:

Name="Satyajit"
case "$Name" in
    #case 1
    "Rajib") echo "Profession : Software Engineer" ;;
    
    #case 2
    "Vikas") echo "Profession : Web Developer" ;;
    
    #case 3
    "Satyajit") echo "Profession : Technical Content Writer" ;;
esac

Output of case-sac statement:

Profession : Technical Content Writer

In the above example, the case-sac statement executed the statement which is a part of the matched pattern here the ‘Name’. Below is the terminal shell pictorial depiction after executing the following script – 

 

String and Numeric Comparisons

The string comparison means in the shell scripting we can take decisions by doing comparisons within strings as well. Here is a descriptive table with all the operators –

Operator Description
== Returns true if the strings are equal
!=  Returns true if the strings are not equal
-n Returns true if the string to be tested is not null
-z Returns true if the string to be tested is null

Arithmetic operators are used for checking the arithmetic-based conditions. Like less than, greater than, equals to, etc. Here is a descriptive table with all the operators –

Operator Description
-eq Equal
-ge Greater Than or Equal
-gt Greater Than
-le Less Than or Equal
-lt Less Than
-ne Not Equal

Below is a simple example of the same –

Example Script:

if [ 10 -eq 10 ];then
echo "Equal"
fi

if [ 'Geeks' == 'Geeks' ];
then
    echo "same" #output
else
    echo "not same"
fi

Output of String and Numeric Comparisons:

Equal
same

In this example first one  (-eq )is a numeric comparison that checks for equality. The second one ( == ) is also check for equality but in strings.  Below is the terminal shell pictorial depiction after executing the following script – 

We will learn more about this concept in the next articles.

Conclusion

In this article we discuss Bash scripting which plays a vital role in automating tasks within the Linux environment. As a command-line interpreter, Bash offers simplicity and ease of use for developers to create scripts that streamline routine operations, manipulate files, and execute complex tasks. While Bash scripts can enhance productivity by avoiding repetitive actions and executing sequences of commands efficiently, they also come with considerations such as managing permissions, handling variables, and implementing decision-making structures. By mastering Bash scripting, users can harness its power to optimize their workflow and enhance system administration tasks on Linux platforms.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads