Open In App

Bash Scripting – Introduction to Bash and Bash Scripting

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
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 is like a robot assistant for your computer. It lets you control your Linux/Unix system by typing commands (e.g., ls to list files). Instead of doing tasks manually, you can write a Bash script—a text file with commands—to automate things like organizing files, installing software, or backing up data.

How to Write Your First Bash Script

Let’s create a simple script that says “Hello, World!”:

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

1. Create a Script File:

Open a terminal and type:

gedit hello.sh # Creates a file named "hello.sh" 

2. Add Code:

Type these lines into the file:

#!/bin/bash # Tells the computer: "Use Bash to run this!" 
echo "Hello, World!" # Prints "Hello, World!" on the screen

3. Make It Executable:

Save the file, then type:

chmod +x hello.sh # Gives permission to run the script 

4. Run It:

Use the below command to execute the script:

./hello.sh 

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.

Key Concepts of Bash Scripting

Here are some key concept of bash scripti:

File Names and Permissions

In the above example, we have saved the file using gfg.sh name and also provided execute permission using chmodcommand. 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 chmodcommand. 

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 in bash

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 –

For more details refer Shell Scripting – Shell Variables

Input and Output in bash

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 – 

For more details refer Shell Scripting – Standard Input, Output and Error

Functions used in bash

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:

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

For more details refer Bash Scripting – Functions

Decision Making in bash

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

Example Script:

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

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 – 

For more details refer Shell Scripting – Decision Making

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 –

OperatorDescription
==Returns true if the strings are equal
!= Returns true if the strings are not equal
-nReturns true if the string to be tested is not null
-zReturns 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 –

OperatorDescription
-eqEqual
-geGreater Than or Equal
-gtGreater Than
-leLess Than or Equal
-ltLess Than
-neNot 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 – 

For more details refer Bash Scripting – String

Applications of Bash Scripts:

  • Automate Repetitive Work: Substitute scripts for manual labor in activities such as renaming files, organizing directories, or issuing alerts.
  • System Updates & Maintenance:  Schedule scripts to update software, remove temporary files, or monitor disk space.
  • Data Processing & Reporting: Scripts can install programs, configure servers, or roll out code to production.
  • Back Up Databases & Files: Schedule scripts to back up important data to cloud storage or external drives.
  • Monitor Systems & Networks: Test server health, monitor downtime, or notify you if a site crashes.
  • Make Custom Tools: Develop mini-apps for unique purposes (e.g., password generators, mass image converters).
  • Schedule Tasks using Cron: Run scripts every hour, day, or year with Bash and cron (Linux scheduler).
  • Manage Files & Permissions: Batch modify file permissions, search/delete big files, or clean cluttered folders.
  • Cross-Platform Scripting: Bash scripts are compatible with Linux, macOS, and Windows (through WSL or Git Bash).

Advantages of Bash Scripts:

  • Easy and Easy to Code: Bash scripts are coded in plain text with easy Linux commands. If you already know how to use the Linux terminal, you can easily write a bash script by putting those commands in a.sh file.
  • Saves Time and Effort: Rather than repeating the same command over and over, a bash script does it all for you at once. This is particularly useful for sysadmins and developers who have to work with multiple systems or environments and is also handy
  • Useful for Scheduling Jobs: You can automate your bash scripts to execute at a given time using tools such as cron—perfect for regular backups, log rotation, or software updates.
  • Running Multiple Commands: One bash script can execute multiple commands sequentially. This simplifies complex tasks such as installing a new server, deploying code, or configuring system parameters.

Disadvantages of Bash Scripts:

  • Errors Can Be Risky: If you make a small mistake in your script—like deleting the wrong folder or overwriting files—it can lead to serious problems. Bash doesn’t have a “undo” button, so testing scripts carefully is verySlower Compared to Compiled Languages important.
  • Each Command Starts a New Process: Every shell command inside a bash script starts a new process. This uses more system resources and can slow things down, especially if the script runs hundreds of commands.
  • Slower Compared to Compiled Languages: Since bash is an interpreted language, scripts run slower than compiled programs (like those written in C or Java). For small tasks, it’s fine, but for performance-heavy tasks, it’s not the best choice.
  • Compatibility Issues Across Systems: Scripts written on one Linux distribution (like Ubuntu) might not work the same way on another (like CentOS) due to different shell environments or command paths. You need to test your script on the target system to ensure smooth execution.

Also Read:

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.



Next Article
Article Tags :

Similar Reads

close