Skip to main content
HomeTutorialsData Analysis

How to Write a Bash Script: A Simple Bash Scripting Tutorial

Discover the basics of bash scripting and learn how to write a bash script.
Nov 2022  · 5 min read

A shell is a kind of computer program that presents an interface to the operating system. The name shell was derived from the fact that it is the outermost layer around the operating system. 

To manage the interaction between users and the operating system, the shell prompts for an input and then interprets that input for the operating system before handling any outputs it receives. This input may be provided via a command line interface (CLI) or graphical user interface (GUI), depending on the operation and the role the computer takes on.

Check out our What is Shell? article to delve deeper into what a shell is and how it can help you. 

Essentially, a shell enables users and other programs to communicate directly with an operating system’s components.

A Primer on Shell Scripting 

Shell scripting is an important yet easy-to-learn (even if you are not from a programming background) part of communicating with a computer’s operating system. By scripting, we are referring to a sequence of shell and operating system commands that are written and then stored in a file: typical operations performed by shell scripts include tasks such as file manipulation, program execution, and printing text. 

Learn more about Data Processing in Shell with our course. 

Learning to perform this simple procedure can save developers a significant amount of development time as certain commands will not have to be manually written repeatedly – it is even possible to schedule scripts to be executed automatically. 

There are several different shells available to Unix and Linux users. For the remainder of this tutorial, we will focus specifically on the Bourne Again SHell (bash), which is an enhanced version of the Bourne shell and is one of the most common command line interfaces for Unix-based operating systems (including Linux). 

What is a Bash Script? 

Bash is a Unix command line interface responsible for interacting with a computer's operating system. Similarly to how movie scripts inform actors of what actions to take, a bash script tells the bash shell what to do. Thus, a bash script is a useful way to group commands to create a program

Any command you could execute directly from the command line can be put into a bash script, and you could expect it to do the same actions as it would from the command line. Alternatively, any command you enter into your bash script could be run directly from the command line, and the result should be the same. In other words, if you know how to interact with your computer from the command line, you already know a fair bit about bash scripting. 

One of the main differences is a bash script is a plain text file that is stored with a .sh extension by convention (they can still run without the .sh extension). 

Another distinction of bash scripts is the “shebang” that occurs on the first line of all scripts. Essentially, the shebang is an absolute path to the bash interpreter made up of a combination of bash “#” and bang “!” followed by the bash shell path. It is used to tell the Linux operating system which interpreter to use to parse the file. 

How to Write a Bash Script

We are going to build a simple “Hello World” bash script example to get you started with bash scripting. If you wish to delve deeper into bash scripting, check out Introduction to Bash Scripting course. 

Step 1: Create a new plain text file 

The first step is to create a new plain text file. You can do this by running the following command from your command prompt: 

notepad hello_world.sh

Note: Executing this command may bring a prompt asking you if you would like to create a new file; select “Yes.” 

Step 2: Specifying the interpreter

On the first line of our script, we must specify which interpreter we would like to use to parse our script. In this scenario, it is Bash. Thus, we must put the shebang in the first line of our script. 

#!/bin/bash

Step 3: Implement commands

The purpose of our bash script is to print “Hello World!” To perform this task, move to a new line and use the echo command followed by the string we would like to print.

echo "Hello World!" 

Once complete, save the file and open up your Git Bash.  

Note: You can download Git Bash from Git downloads. Simply select the version of Git that corresponds with your operating system. 

Next, run the following command: 

bash hello_world.sh

This should output “Hello World!” as seen in Figure 1. 

A call to the bash script returns “Hello World!” in the terminal.

Figure 1: The output of our Bash script

 

How to Capture User Input in Bash Scripts

Now you know how to write a simple “Hello World!” script. Let’s take a look at how we could use bash to write scripts that require input from the user. In this example, we will create an activity generator, which will ask the user for their name and then choose a random activity to invite the user to participate in from an array of activities. 

The steps to create the file are the same as in How to Write a Bash Script – the difference are the commands we enter into our bash script. 

  1. Create a new plain text file from the command prompt using notepad.
notepad generate-activity.sh 
  1. Specify the bash interpreter by entering the shebang in the first line of the script.
#!/bin/bash
  1. Write the commands to run the script and then save the file.

Now when we call our bash script from the terminal, we should expect to see the same output as in Figure 2. 

#!/bin/bash

# Greet user and request their name
echo "The activity generator"
read -p "What is your name? " name

# Create an array of activities
activity[0]="Football"
activity[1]="Table Tennis"
activity[2]="8 Ball Pool"
activity[3]="PS5"
activity[4]="Blackjack"

array_length=${#activity[@]} # Store the length of the array
index=$(($RANDOM % $array_length)) # Randomly select an index from 0 to array_length

# Invite the user to join you participate in an activity
echo "Hi" $name, "would you like to play" ${activity[$index]}"?"
read -p "Answer: " answer

Demonstrating the generate-activitysh scriptFigure 2: Demonstrating the generate-activity.sh script.

How to Create a Function in a Bash Script

In programming, functions are used to bundle a set of repeated instructions together – learn more about Functions in Python. The purpose of writing functions is to avoid writing the same code constantly, and it also makes your code more readable. 

A bash function may be considered a typical function: a set of commands that can be called several times. However, bash functions are slightly more limited when compared to the majority of programming languages (i.e., bash functions do not allow you to return a value when called). 

Before we create a bash script using a function, let’s take a look at the syntax for declaring a bash function. We can define a function by writing a function name, followed by parentheses and curly braces for the function's body – this is the most common way to write a bash function. Here is it looks in code: 

# Most common way to write a bash function.
example_function () {
  commands
{

The other way to format a bash function is to begin the line with the reserved bash keyword function, then the function name and curly braces for the function body – we do not need the parentheses. 

# Another way to write a bash function.
function example_function {
  commands
{

Defining the function will not execute the commands. To invoke a bash function, you must call the function name, as follows: 

#!/bin/bash

# A hello world bash function
hello_world () {
  echo "Hello World!"
}

# Invoking the hello_world function
hello_world

Above, we created a  hello_world function that prints “Hello World!” when the bash script is run.

Passing arguments to bash functions

Arguments are variables used in a specific function. In bash, we can not pass arguments to functions like you would in high-level programming languages such as Python, Julia, etc. Instead, bash functions have their own command line argument and we can pass parameters to a function by placing them after a call to the function name – separated by a space if there are multiple arguments.

In essence, function arguments are treated as positional parameters and shell variables ($1, $2, ..., $n) are used to access arguments passed to the function. 

#!/bin/bash
greet () {
  echo "Hello $1 $2"
}

greet "John" "Doe" 

In the bash script above, we passed two arguments, John and Doe,  to our greet function. When the bash script is run now, we should see the following output:

Hello John Doe

Writing “If” Statements in Bash

“If” statements are conditional statements used in programming languages. If a statement is proven to be true, then a condition would run. This functionality enables us to determine the circumstances under which a certain piece of code shall be executed. 

In bash, we start the conditional with an if statement and end it with fi (if spelled backward). Here is an example bash script with if conditionals: 

#!/bin/bash

read -p "Give me a number: " number
if [ $number -gt 10 ];
then
  echo "Your number is greater than 10."
fi

In the bash script above, the user is asked to provide a number. If the number provided by the user is greater than 10, then “Your number is greater than 10” will be outputted to the terminal, but if it is not, the program will end. Figure 3 is an example of us passing a number larger than 10. 

Using if statements in Bash scripts

Figure 3: Using “if” statements in Bash scripts

Wrap-up 

Bash scripts are a useful way to elegantly group commands together. You could leverage the power of a bash script for a number of use cases, such as executing a shell command, running multiple commands together, customizing administrative tasks, performing task automation, and more. 

By following the steps provided in the tutorial above, you now know how to create a simple script to print “Hello World!” using Bash. 

Topics

Bash Scripting Courses

Course

Data Processing in Shell

4 hr
18K
Learn powerful command-line skills to download, process, and transform data, including machine learning pipeline.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

You’re invited! Join us for Radar: The Analytics Edition

Join us for a full day of events sharing best practices from thought leaders in the analytics space
DataCamp Team's photo

DataCamp Team

4 min

10 Top Data Analytics Conferences for 2024

Discover the most popular analytics conferences and events scheduled for 2024.
Javier Canales Luna's photo

Javier Canales Luna

7 min

A Data Science Roadmap for 2024

Do you want to start or grow in the field of data science? This data science roadmap helps you understand and get started in the data science landscape.
Mark Graus's photo

Mark Graus

10 min

A Complete Guide to Alteryx Certifications

Advance your career with our Alteryx certification guide. Learn key strategies, tips, and resources to excel in data science.
Matt Crabtree's photo

Matt Crabtree

9 min

Making SMARTER™️ Decisions with Lori Silverman, author of Business Storytelling for Dummies

Richie and Lori cover common problems in business decision-making, connecting decision-making to business processes, the role of data visualization and narrative storytelling, the SMARTER™️ decision-making methodology and much more.
Richie Cotton's photo

Richie Cotton

62 min

Mastering Bayesian Optimization in Data Science

Unlock the power of Bayesian Optimization for hyperparameter tuning in Machine Learning. Master theoretical foundations and practical applications with Python to enhance model accuracy.
Zoumana Keita 's photo

Zoumana Keita

11 min

See MoreSee More