Course Overview

/

Bash Conditional Statements

Bash Conditional Statements

Conditional statements are used to execute specific commands only if a certain condition is met. In Bash we use the key words “if”, “elif”, and “else” to guide the script through the different potential conditions. The “fi” keyword is then used to mark the end of the statement.

4th Bash Script

The forth bash script created is:

These 3 statements demonstrate the ability to apply conditions to simple and complex requests. It is possible to use conditional statements that take multiple forms of input and can provide a relatively short piece of code that will run multiple checks against an input.

Statement 1

The first statement shows the syntax needed to execute a conditional statement (if statement ended with a fi command). The simple condition within this script is a comparison of x and y and if the value of y is bigger than x, only then will the echo command be executed

Statement 2

The second statement uses “elif” and “else” to expand on statement 1. When comparing two integers, there are three potential outcomes:

· x is bigger than y

· x is smaller than y

· x is the same as y

elif is the keyord use for “else if”, this means that as the condition of the previous if statement has not been met, another if statement is provided. Once all of the elif statements have been checked, if the condition has not been met, the “else” keyword is used as a catch-all statement to mean “if none of the above if statements are correct, then do this”.

Statement 3

The third statement shows how we can use conditional statements to create a more complex piece of code. We can pass parameters into a function that is using a conditional statement and have it provide only the appropriate output.

This example shows how we can use both strings and integers as part of these conditions and defines the variables to make the code easier to read.

This is because bash will assign the vales being passed when the function is executed the appropriate $1 and $2 values. The code would work just as well if it were coded in the following way however it is down to individual scripters how they choose to document and define their scripts

It should be noted that the syntax to call the function in Bash is to name the function and pass the values, no parentheses are needed.