Getting Started with Bash Script : A Simple Guide

by Aug 14, 2022IoT Programming

Introduction

In this tutorial, we will be looking into Bash Script – a tool used by developers to increase productivity and manage tasks. A lot of professionals use it for tasks such as system administration, data crunching, web app development, automated backups, etc. Bash is most commonly run on Linux OS.

What is a Bash Script?

In simple words, Bash Scripts are plain text files that contain a series of commands. These commands are the same ones that we type in a terminal command line. So the difference here is that instead of typing the commands directly on the command line, we type them in a plain text file. These files have a .sh extension.

Every bash script file starts with the line #!/bin/bash, where #! is referred to as the SheBang. The rest of the line consists of the path to the interpreter specifying the location of the bash shell in the OS.

The SheBang(#!) is known as the path directive. This is because it denotes an interpreter to execute the script lines and is used for the execution of scripts like Bash. NOTE: Be careful about the formatting of SheBang. Incorrect formatting can result in the malfunctioning of the script file.

Some common commands used in Bash are:

./ – For execution of a bash script

# – For commenting lines within the script

echo – For printing lines

Advantages of Bash Script

1. A major advantage is the simplicity of its creation. It can be made without any programming knowledge.

2. Bash Scripts can be automated, which helps in dealing with repetitive tasks easily.

3. It’s very time-saving and cost-effective

4. We can run multiple commands in the same script

5. We can create and edit text files using bash script

Bash Scripting – Examples

First, let’s start by creating a new bash script file. Remember that these files must contain the extension .sh in their file name. First, start the Linux terminal and type in cd Desktop/ to change the directory to Desktop. Next, type the command touch followed by the file name (eg. bScript.sh) to create our file as follows:

cd Desktop/
touch bScript.sh

Next, access the Desktop folder from the Files option. You will be able to see the newly created bash script file

1. Creating a Hello World Script

For every bash script file, we need to type #!/bin/bash as the first line. To display a line, we use the echo command followed by the text within double quotes

#!/bin/bash

echo "Hello World"

Following this, we go to the terminal to run the script file. However, this script file is not yet executable. Using the ls -l command, we can see the files and directories. Here, we can notice that the script name is not highlighted, indicating that it is not executable. So, we use the chmod +x command followed by the file name to make it executable as shown below:

cd Desktop/
ls -l

chmod +x bScript.sh
ls -l

Now, when we type ls -l command, we can see that the file name appears highlighted, which means that it is executable.

Next, we execute our Hello World script using ./ followed by the file name as shown below:

./bScript.sh

2. Printing strings on the same line (-n command)

Next, we will see how to display two strings on the same line. We use the -n command to implement this. The difference between using -n command and not using -n command is as follows:

#!/bin/bash

echo -n "With"
echo "-n command"

echo "With"
echo "no -n command"
cd Desktop/
./bScript.sh

3. Displaying multiple strings on the same line

It is possible to display multiple strings on the same line by typing the echo command followed by the strings in double quotes separated by space.

#!/bin/bash

echo "Using" "multiple" "strings" "on" "same" "line"
cd Desktop/
./bScript.sh

4. String continuation character (\)

In Bash, we use a backslash (\) as a string continuation character.

#!/bin/bash

echo "Using" "String" \
                        "continuation" "character"

The strings are written in two lines with just a single echo command. Normally, it would cause an error, but by adding a backslash, it is considered the same line. As a result, we get the following output:

cd Desktop/
./bScript.sh

5. Spacing words using tab character (\t)

We can space the words within a string using the tab character. For this, first, type the echo command followed by -e. Following this, type in the string with \t in between the words.

#!/bin/bash

echo -e "Using\ttab\tcharacter"

As a result, we get the following display:

cd Desktop/
./bScript.sh

6. Using the newline character (\n)

We can print the words within a single string in multiple lines by using the newline character. To do so, type the string with the words separated by \n.

#!/bin/bash

echo -e "Using\nnewline\ncharacter"

On executing the file, the result will be as follows:

cd Desktop/
./bScript.sh

7. Displaying words within single quotes and double quotes

In Bash Scripting, we can display words within single quotes in the normal way.

However, for words within double quotes, we need to type \” before and after the word./

#!/bin/bash

echo "Welcome to 'BashScript'"

echo "Welcome to \"BashScript\""

Following this, execute it on the terminal.

cd Desktop/
./bScript.sh

8. Displaying all the commands

Bash provides us with the option to display all the commands used in a script along with their result. This is by adding -x to the first line as follows:

#!/bin/bash -x

echo "Welcome"
echo "to"
echo "BashScript"

On executing the Script, we get the following display:

cd Desktop/
./bScript.sh

9. Writing to a text file using Script

Through the Bash Script, we are able create a new text file and write data into it. For writing a text into a text file, we use the > ./ symbols followed by the text file name. Look at the example below:

#!/bin/bash

echo "Hello World" > ./file.txt

Next, we execute the script file by calling it. Following this, we use the ls command to check the list of files created. If executed correctly, the name of the text file created will be displayed.

So, as the next step, we can view the contents of the text file using the nano editor. Use the nano command followed by the text file name.

cd Desktop/
./bScript.sh
ls
nano file.txt

As a result, the nano editor shows up as follows:

If you want to verify whether the text file is created, go to desktop folder as it is usually created in the location folder of the bash script file

10. Append text to a text file

Bash Script also provides us the option to append text to a text file. For this purpose, we type in the text followed by >> ./ and the text file name. Refer to the example given below:

#!/bin/bash

echo "Hello World!" > ./file.txt

echo "Welcome to the text file!" >> ./file.txt

Next, execute the script in the terminal

cd Desktop/
./bScript.sh

To test whether the text is added to the file, let’s check the text file once again.

11. Single Variable Usage

It is possible to create variables containing strings, integers, etc in bash script. We can display the value using $ symbol followed by the variable name. Let us look at an example for a better understanding.

#!/bin/bash

var="Hello!"
echo $var

var1=35
echo $var1

NOTE: Do not leave space between the variable name and the “=” operator. As a result of executing the script, we get the following display:

cd Desktop/
./bScript.sh

12. Multiple Variable Usage

Bash script also supports the usage of multiple variables. Look at the following example:

#!/bin/bash

var1="this is variable 1"
var2="this is variable 2"

var3="${var1} ${var2}"

echo "${var3}"

We get the following display on executing the script in the terminal

cd Desktop/
./bScript.sh

Conclusion

So, in this tutorial, we have looked into Bash Script in detail, and also demonstrated some examples to get started with bash scripting. Bash Scripting is a popular and powerful tool used by professionals to make their work easier. Hope that this tutorial was informative and evoked your curiosity about Bash Scripting.

To know more about bash scripts, you can check the official documentation by clicking here.

Happy Learning!

Creating a multiplication Skill in Alexa using python

Written By Monisha Macharla

Hi, I'm Monisha. I am a tech blogger and a hobbyist. I am eager to learn and explore tech related stuff! also, I wanted to deliver you the same as much as the simpler way with more informative content. I generally appreciate learning by doing, rather than only learning. Thank you for reading my blog! Happy learning!

RELATED POSTS

Advanced Generics: Higher-Order Functions

Advanced Generics: Higher-Order Functions

In our journey through TypeScript generics, we've covered the basics, interfaces, and classes. Now, it's time to explore advanced concepts by combining generics with higher-order functions. These functions, which take other functions as arguments or return them,...

Basic Usage of Generics in Typescript

Basic Usage of Generics in Typescript

Keypoints Show how to declare generic functions and classes in TypeScript. Provide examples of generic functions that work with different data types. Demonstrate the use of built-in generics like Array<T> and Promise<T>. Here's the content...

How to Extract REST API Data using Python

How to Extract REST API Data using Python

Introduction In this tutorial, we will be discussing in detail on how to extract REST API data using Python. It is one of the most popular APIs and is used by a majority of applications. We will be using VS code editor for executing the python code. The extracted API...

Create a Simple ReactJs Application – Part 1

Create a Simple ReactJs Application – Part 1

ReactJs is one of the famous front-end open-source libraries of JavaScript developed by Facebook. It aims to allow developers to quickly create fast user interfaces for websites and applications. In this blog, we will create a simple and basic ReactJs...

Create a Simple ReactJs Application – Part 2

Create a Simple ReactJs Application – Part 2

In the tutorial's last part, we discussed about ReactJs and how to run a simple react app on a web browser. In this part, we will dig more into some interesting stuff, such as creating a home, about us, and contact pages. Click here for the first part - Create a...

Basic MATLAB Commands and its Functionality

Basic MATLAB Commands and its Functionality

MATLAB is a language used by engineers and scientists for computational mathematics. It is used for developing algorithms, analyzing them, and also for creating models and applications. MATLAB also helps in developing applications using by deploying applications,...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....