The Wayback Machine - https://web.archive.org/web/20240623215220/https://www.geeksforgeeks.org/bash-scripting-introduction-to-bash-and-bash-scripting/
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.



Previous Article
Next Article

Similar Reads

Bash Scripting - How to Run Bash Scripting in Terminal
In this article, we are going to see how to run bash script in terminal. For example, we create a bash file set of instructions or commands ( known as bash script ), and through command, we can run this file in terminal. Let see how to run bash script in terminal. Example 1 : In this example we print or echo some text on screen with the help of a t
2 min read
Bash Scripting - Working of Bash Scripting
Bash Scripting is a crucial component of Linux's process automation. You can write a series of commands in a file and then execute them using scripting. A Bash script is a plain text file with a set of commands inside of it. These commands are a combination of ones we typically type on the command line ourselves (like ls or cp, for instance) and ot
6 min read
Bash Scripting - Difference between Zsh and Bash
A shell is an environment in which various commands can be executed, it provides an interface between the user and the UNIX system. Basically, a shell is a command-line interpreter which interprets the commands given by the user, it can also read the combination of such commands which is known as a shell script. The shell provides us with an enviro
2 min read
Bash Scripting - Bash Read Password without Echoing back
Generally, you can see on the login page, whenever we type a password either it show dot (•) or asterisk (*) instead of a password. They do so because to protect our system or account. In such a case, the login page read the password and in place of the password, it will show a dot or asterisk. And in some cases, a dot or asterisk also may not appe
3 min read
Bash Scripting - Write Output of Bash Command into Log File
Let there are some situations in which you have to save your output in a file ( generally called log file). Output can be user details ( username, password, Gmail, etc. ), products record ( buying or selling any goods ), or simply any kind of data that you can store in a log file. Let see how to write the output of the bash command into a log file.
4 min read
Bash Scripting - Bash Echo Command
In this article, we are going to see the echo command. The Echo command is a built-in command feature for Unix / Linux which is generally used to display the text or message on the screen. Syntax : $ echo [option][text]For Example : $ echo Geeks For GeeksOutput : Geeks For Geeks There are generally three options:-n: It does not print the trailing n
2 min read
Shell Scripting - Difference between Korn Shell and Bash shell
Korn Shell: Korn Shell or KSH was developed by a person named David Korn, which attempts to integrate the features of other shells like C shell, Bourne Shell, etc. Korn Shell allows developers to generate and create new shell commands whenever it is required. Korn shell was developed a long year back as it is older than the BASH shell and it has fe
3 min read
Leap Year Program with Bash Shell Scripting in Windows
Accurately the Earth has 365.24 days per year, to correct the approximation and keep track of the Solar Calendar the idea of leap year has been introduced to Gregorian Calendar. A leap year comes once every four years. In contrast, it has 366 days with regular years, having 365 days. Mathematical approach to check:Every year is a Leap year if it is
1 min read
Bash Scripting - How to read a file line by line
In this article, we are going to see how to read a file line by line in Bash scripting. There might be instances where you want to read the contents of a file line by line using a BASH script. In this section, we will look at different ways to do just that. We will use BASH commands and tools to achieve that result. We make use of the read and cat
3 min read
Bash Scripting - How to check If File Exists
In this article, we will write a bash script to check if files exist or not. Syntax :test [expression][ expression ][[ expression ]] Here, in expression, we write parameter and file name. Let us see some parameters that can be used in the expression: - -f: It returns True if the file exists as a common ( regular ) file.-d: it returns True if direct
6 min read
Article Tags :