Basics Of Bash Scripting
Tags: bash, linux, cloud
Published: 2022-02-20 05:41:44

## What is a Shell
The shell is a computer program, it takes each command and passes it to the operating system kernel to be executed. It then displays the results of this operation on your screen.
Different systems may use different shells. The most commonly available shells are:
- Bourne shell (sh)
- Bourne Again Shell (bash)
- C shell (csh)
- Z Shell (zsh)
- Korn shell (ksh)
by using `cat /etc/shells`, We can see the list of available shells in our Linux system.

## Shell Script
A shell script is a file that contains a list of commands that are executed sequentially by the Unix shell. The main components of a Shell Script are :
- Shebang ( #!/bin/bash) 
- Comments (starts with #)
- Actual Commands of Linux( ls, cd, mkdir, chmod etc...)
- Statements ( If, for , while etc.,)

In order to execute, the shell script file need to have executable permissions. 

Sample Shell Script :
```
#!/bin/bash
# script to print - Hello World!
echo "Hello World!
```
It is a basic script, that prints hello world to the terminal. Here the first line is called as "shebang" which tells the shell to run the file as bash script. The second line is a comment which is ignored while execution. And the `echo` command which print the stdout to terminal screen.

![Screenshot 2022-02-12 at 9.17.35 AM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1644637675174/E-nZxpc79.png)

We can execute the script either by Bash source, or execute it as a shell-script by making it executable (using `chmod`) from the path. 
## Variables
We all know,  we need variables to store some value which we are gonna use repeatedly. Bash has variables using which you can store values. Let's create and use some variables in Bash.
```
#!/bin/bash
name = srinivas
echo $name
```
To create a variable, we simply write the variable name and assign the value to the variable. To access the variable add $ sign before the variable name.

![Screenshot 2022-02-12 at 9.27.48 AM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1644638396480/AFAewUdRL.png)
## Conditional statements
### If Statement
```
if COMMAND_TO_TEST
then
  STATEMENTS
fi
```
The `if` statement starts with the 'if' keyword followed by the conditional expression and the then keyword. The statement ends with the `fi` keyword.

If the COMMAND_TO_TEST evaluates to True, the STATEMENTS gets executed. If COMMAND_TO_TESTreturns False, nothing happens; the STATEMENTS get ignored.
```
#!/bin/bash

echo -n "Enter a number: "
read number

if [[ $number -gt 100 ]]
then
  echo "The variable is greater than 100."
fi
```
The script will prompt you to enter a number. When you enter 120, the test command will evaluate to true because 120 is greater than 100, and the echo command inside the then clause will be executed.

![Screenshot 2022-02-12 at 7.24.10 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1644674115890/jT4kRRgPx.png)
The `-gt` in the script is numeric comparison - greater than. The following table lists comparison operators for both numbers and strings.

![Screenshot 2022-02-12 at 7.26.49 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1644674222334/YGrfECDXa.png)

### if...else Statement
The Bash if..else statement takes the following form:
```
if COMMAND_TO_TEST
then
  STATEMENTS1
else
  STATEMENTS2
fi
```
If the COMMAND_TO_TEST evaluates to True, the STATEMENTS1 will be executed. Otherwise, if COMMAND_TO_TEST returns False, the STATEMENTS2 will be executed. You can have only one else clause in the statement.

Let’s add an else clause to the previous example script:

![Screenshot 2022-02-12 at 7.51.43 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1644675721972/25ZV3cLjJ.png)
When you enter 100, the test command will evaluate to false and else block executes. 
### if...elif...else Statement
```
if COMMAND_TO_TEST
then
  STATEMENTS1
elif COMMAND_TO_TEST
then
  STATEMENTS2
else
  STATEMENTS3
fi

```
The conditions are evaluated sequentially. Once a condition returns True, the remaining conditions are not performed, and program control moves to the end of the if statements.

![Screenshot 2022-02-12 at 7.57.32 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1644676069460/i9FnPzW1c.png)

BASH also allows you to nest if statements within if statements. You can place multiple if statements inside another if statement and you can also use logical operators like `OR` and `AND` operators allow you to use multiple conditions in the if statements.

## Loops
Loops are useful when you want to run a series of commands repeatedly until a certain condition is reached.

There are three basic loop types in Bash scripting. 
- for loop
- While loop
- until loop
### for loop
The basic `for` loop in Bash looks like:
```
for item in [LIST]
do
  [COMMANDS]
done
```
In the below example, the loop will iterate over a each number in the list.
```
for number in 0 1 2 4 5 6 7 8 
do
  echo "number : $number"
done
```
![Screenshot 2022-02-13 at 9.17.56 AM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1644724222870/TOqLIldeu.png)
For looping over a number range, we can use `{0..8}`. In the latest versions of Bash, it is also possible to **specify an increment** when using ranges. The expression takes the following form:
```
for number in {0..10..2} 
do
  echo "number : $number"
done
```

![Screenshot 2022-02-13 at 9.20.02 AM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1644724237697/QWkuRcCzd.png)
We can also use the `for` loop as follows:
```
for ((INITIALIZATION; TEST; STEP))
do
  [COMMANDS]
done

```

![Screenshot 2022-02-13 at 9.28.52 AM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1644724747723/p28CTC0_g.png)
### `break` and `continue` 
We all know, the break and continue statements can be used to control the loop execution. 

- The **break statement** terminates the current loop and passes program control to the statement that follows the terminated statement. It is usually used to terminate the loop when a certain condition is met.

- The **continue statement** exits the current iteration of a loop and passes program control to the next iteration of the loop.

### Bash `while` loop
The while loop is used to performs a given set of commands an number of times as long as the given condition evaluates to true.

The Bash while loop takes the following form:
```
while [CONDITION to TEST]
do
  [COMMANDS to EXECUTE]
done
```
In the following example, for each iteration, the current value of the variable `i` is printed and incremented by one.
```
number=0
while [ $number -le 5 ]
do
  echo "Number: $number"
  ((number++))
done
```
The above script loops as long as `i` is less than 5.

![Screenshot 2022-02-13 at 9.48.44 AM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1644725942070/Q6gWDRGj-.png)
### Bash `until` loop
The `until` loop is used to execute a given set of commands as long as the given condition evaluates to false.

The Bash until loop takes the following form:
```
until [CONDITION to TEST]
do
  [COMMANDS to EXECUTE]
done
```
In the following example, on each iteration the loop prints the current value of the `number` and increments the variable by one.
```
#!/bin/bash
number=0
until [ $number -gt 3 ]
do
  echo "Number: $number"
  ((number++))
done
```
The loop iterates until the variable has a value greater than three. The script gives the following output.

![Screenshot 2022-02-13 at 9.56.27 AM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1644726403689/RvDZ_2MUD.png)

The `while` and `until` loops are similar to each other. The main difference is that the while loop iterates as long as the condition evaluates to `true` and the until loop iterates as long as the condition evaluates to `false`.
### Functions in Bash
Function are part of any programming language , we can define the function as follows:
```
function_name () {
  commands to execute
}
```
Let's look at the following example which prints "hello world" to screen.
```
#!/bin/bash
helloworld () {
   echo "Hello_world"
}
helloworld
```
If you run the script, it will print `Hello_world`

![Screenshot 2022-02-13 at 10.07.42 AM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1644727077401/bjKFFIGhY.png)
We can also declare a function using the keyword `function` just like we do in most of the programming languages.

![Screenshot 2022-02-13 at 10.10.01 AM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1644727279891/Ihhi-2yLp.png)

Unlike functions in “real” programming languages, Bash functions don’t allow you to return a value when called. 
The return status can be specified by using the return keyword, and it is assigned to the variable $?. The return statement terminates the function. You can think of it as the function’s exit status .
```
#!/bin/bash
my_function () {
  echo "Test of Return"
  return 7
}

my_function
echo $?
```

![Screenshot 2022-02-13 at 10.16.54 AM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1644727665702/-z3Svgqqg.png)
A Bash function is a block of reusable code designed to perform a particular operation. Once defined, the function can be called multiple times within a script.

Connect with me on [Linkedin](https://www.linkedin.com/in/srinivas-karnati/), [Twitter.](https://twitter.com/__karnati)