What is Linux Bash Scripting

What is Linux Bash Scripting? Well, Bash is a command line interpreter. And Linux Bash Scripting is for executing a series of commands in Linux Shell. It may seem intimidating at first, but we would look at a few Linux bash scripting examples and see that it’s not that difficult.   

Prerequisite

Table of Content

  • Basic Hello World Bash Script  
  • Variables in Bash Script 
  • Reading User Input in Bash Scripting  
  • Arrays in Bash Scripting  
  • IF / Else Statements in Bash Scripting  
  • Functions in Bash Scripting  
  • Loops in Bash Scripting 
  • Practice Questions

Linux Bash Scripting

What is Linux bash scripting? 

Bash scripting is basically a shell script which is actually a program that is executed by a command line interpreter. They are a group of many commands to be run sequentially to perform a task. They are all the basic Linux commands that we already know and use in Linux Terminal.  

Let’s see some Linux bash scripting examples. 

1. Basic Hello World Bash Script 

First, we need to create a shell script file. Execute the following command to create and open a shell script with ‘nano’ text editor. 

				
					nano script.sh 
				
			

Now paste the below code inside it. 

				
					#! /bin/bash 
myText="Hello World" 
# creating and initializing a variable 
  
echo $myText 
# printing the value of the variable 
				
			

Explanation: 

  • In line 1, we have to mention the script interpreter after the shebang (#!). Since we are performing bash scripting, the interpreter is at /bin/bash. 
  • In line 2, we are creating a variable myText and then insert a string value in it. 
  • In line 5, we are printing the value of the variable out in the console.  

By default, a shell script is not executable because it does not have the rights yet. Therefore, we need to give a script.sh executable rights before we can run our bash script. You can find more details for Permissions and rights for Linux here. 

To quickly give executable rights, exit the nano text editor and execute the below command. 

				
					sudo chmod +x script.sh 
				
			

Now it’s time to finally run the bash script. To execute the bash script, enter the below command where the script.sh file is located. 

				
					./script.sh 
				
			

OUTPUT

Hello World

2. Variables in Bash Script 

				
					#! /bin/bash 

var1="PROGRAMATICALLY!" 
echo $var1 
				
			

Explanation: 

  • Line 1 is where you mention your script interpreter (/bin/bash). 
  • Line 2 is where we are creating a variable named var1 and giving it a value. 
  • Line 3 is simply printing out the variable’s value. 

 

Execute the file and the output should be as follows: 

PROGRAMATICALLY

Global vs Local variable 

It follows the same concept as in any other programming language. A global variable is identifiable and accessible throughout the bash script. Whereas local variables are only accessible in their defined scope, such as inside a function. 

				
					#! /bin/bash 

var1='my global variable' 
 
function testFunction { 
    local var1='my local variable'
    echo $var1 
} 
 
echo $var1 
testFunction 
				
			

Explanation: 

  • The global variable is defined outside of the function and the local variable is defined inside.  
  • When the script is executed, the global variable was called first and then afterward the testFunction was called which printed the local variable.  

The output should look like this: 

my global variable
my local variable

3. Reading User Input in Bash Scripting 

It’s always a great idea to make your script dynamic. The ‘read’ command is used to take in user input in Bash Scripting. Copy the code below and execute the Bash Script. The output is also shown in the image below as well. 

				
					#! /bin/bash
  
echo -e "Who is your most favorite Avengers Character:  " 
read  val1 
echo "Your answer was: $val1" 
  
echo -e "Which 2 Avengers movie were your favorite: " 
read var1 var2 
echo -e "Your answer was: \"$var1\" \"$var2\"" 
  
echo -e "Which one is better, Marvel or DC? " 
# read command now stores a reply into the default build-in variable $REPLY 
  
read 
echo "You answer was $REPLY" 
  
echo -e "Who are your favorite Marvel Villains? " 
# -a makes read command to read into an array 
read -a villains 
echo "My favorite Marvel villains are ${villains[0]}, ${villains[1]} and ${villains[2]}." 
				
			

OUTPUT

User Input for Bash Scripting in Linux
User Input for Bash Scripting in Linux

4. Arrays in Bash Scripting 

In the below Linux Bash Scripting example, we are initializing an array and then iterate through it using For Loops and print the elements as output. 

There are 2 methods to initialize an array in Bash Scripting. Let’s see both of them.

				
					
# Method 1
arr=( 'CentOS Linux' 'Fedora Linux' 'Ubuntu Linux' 'Mint Linux' ) 


# Method 2
arr=[]
arr[0]='CentOS Linux'
arr[1]='Fedora Linux'
arr[2]='Ubuntu Linux'
arr[3]='Mint Linux'
  

				
			

After initializing the array, let’s see how to print them out in the console using loops. Copy the code below and execute the Bash Script.

				
					#! /bin/bash
  
# Initializing Array with 4 items 
arr=( 'CentOS Linux' 'Fedora Linux' 'Ubuntu Linux' 'Mint Linux' ) 
  
# get number of items in the array 
# @ represents all the items together 
total=${#arr[@]} 
  
  
# for loop to print items in array 
for (( i=0; i<$total; i++ )); do 
    echo ${arr[${i}]} 
done 
				
			

OUTPUT

Debian Linux
Redhat Linux
Ubuntu Linux
Mint Linux

5. IF / Else Statements in Bash Scripting 

In IF/Else statements, you would need to specify when you want to close the statement by writing FI at the end.  

The conditions have their unique annotations, whose chart I’ve mentioned below the code. Other than that, it’s very straightforward.  

				
					#! /bin/bash
  
echo -e 'Enter the speed of car: ' 
read speed 
  
# Check if the speed is less than 80 
if [ $speed -le 80 ]; then 
    echo "You are in the right range of speed." 
elif [ $speed -gt 0 ] && [ $speed -lt 35 ]; then  
    echo "You are driving too slow!" 
elif [ $speed -gt 100 ] || [ $speed -lt 0 ]; then  
    echo "Speed entered is incorrect!" 
else  
    echo "You are driving way too fast!" 
fi 
				
			

Bash Script: Mathematical Operators 

-lt 

< 

-gt 

> 

-le 

<= 

-ge 

>= 

-eq 

== 

-ne 

!= 

Bash Script: String Operators 

= 

equal 

!= 

Not equal 

< 

Less than 

> 

Greater than 

-n var1 

string variable var1 is not empty 

-z var1 

string variable var1 is empty 

6. Functions in Bash Scripting 

We have already seen a basic example of functions in bash Scripting. Let’s look at a few more examples of it. Copy the code and execute the bash script. 

				
					#! /bin/bash
  
# printing a basic string 
function testFunction_1 { 
        echo 'You called Function 1' 
} 
  
# printing a passed in argument 
function testFunction_2 { 
        echo $1 
} 
  
# calling another function inside a function 
function testFunction_3 { 
        echo testFunction_1
} 
  
  
# CALLING ALL FUNCTIONS 
  
testFunction_1 
  
testFunction_2 "Hello World!" 
  
testFunction_3
				
			

OUTPUT

You called Function 1
Hello World!
testFunction_1

7. Loops in Bash Scripting 

In LOOPS, you would need to specify when you want to close the loop by writing done at the end.  

The below code is basic FOR Loop which prints all the files present in /etc/ directory. 

FOR LOOP in Bash Scripting 

				
					#!/bin/bash
  
# bash for loop 
for i in $( cat /etc/passwd ); do 
	echo $i 
done 
				
			

OUTPUT


sysctl.conf
sysctl.d
systemd
terminfo
timezone
tmpfiles.d
ucf.conf
update-motd.d
vim
xattr.conf
xdg

WHILE LOOP in Bash Scripting 

				
					#!/bin/bash
  
# initializing an int variable 
counter=0 
  
# bash while loop 
while [ $counter -lt 10 ]; do 
	echo counter = $counter 
	let counter=counter+1 
done
				
			

OUTPUT

counter = 0
counter = 1
counter = 2
counter = 3
counter = 4
counter = 5
counter = 6
counter = 7
counter = 8
counter = 9

Loop through an Array in Bash Scripting  

Following is the same example that we saw in the Arrays in Bash Scripting section.  

				
					#! /bin/bash
  
# Initializing Array with 4 items 
arr=( 'CentOS Linux' 'Fedora Linux' 'Ubuntu Linux' 'Mint Linux' ) 
  
# get number of items in the array 
# @ represents all the items together 
total=${#arr[@]} 
  
  
# for loop to print items in array 
for (( i=0; i<$total; i++ )); do 
    echo ${arr[${i}]} 
done
				
			

OUTPUT

Debian Linux
Redhat Linux
Ubuntu Linux
Mint Linux

FOR EACH LOOP

Let’s print out the same array list using a ‘For Each’ style loop. Copy the code below:

				
					#! /bin/bash
  
# Initializing Array with 4 items 
arr=( 'CentOS Linux' 'Fedora Linux' 'Ubuntu Linux' 'Mint Linux' ) 

# arr[@] Implies all positional parameters in the list.
for i in ${arr[@]}
do
    echo $i
done
				
			

Debian Linux
Redhat Linux
Ubuntu Linux
Mint Linux

8. Bash Scripting Sample practice Questions

Q1. Take an Integer user-input ‘n’. Create an array of random words and only print those words out which are longer than the length of ‘n’.

Q2. Take 5 integers as user input and store it in an array and sum all the numbers using loops. 

Q3. Print out any Math table using While Loop.

Q4. Create a Function that takes in an integer parameter and checks which range it falls in. 
1 – 50
50 – 100
100 – 1000

And that’s a wrap! 

These commands will only work on a LINUX terminal. And a common way to run Linux with Windows is to start a Virtual Machine using VMware. 

I hope this article helped you learn about What is Linux Bash Scripting. You may also want to learn Basic Linux commands hands-on or Users, Groups, and Permissions in Linux. Please like this article and leave your reviews in the comment section below. 

Have a great one!