1. Home
  2. Bash
  3. Bash Tutorial
  4. Bash – If-else

Bash – If-else

Bash if else Statment

If-else is the decision making statements in bash scripting similar to any other programming. Where execution of a block of statement is decided based on the result of if condition. If it evaluates a condition to true, then if block code is executed, on the false condition, the else block code is executed, which is optional.

Syntax:

basically, there are 4 types of if statements.

  • if statement
  • if-else statement
  • else-if ladder statement
  • nested if statement

1. Bash – if Statement Example

This is the basic if condition, where if an expression evaluates to true a block of code is executed.

bash if example

For example, take input of any number from the user and check if the given value is greater than 10.

2. Bash – if-else Statement Example

In case the condition evaluates to false then else block statements are executed (if available).

bash if else example

Using the same script as above. Only if a user-entered value is greater than 10 then print “OK”. If the value equals to 10 or less then print “Not OK”

3. Bash – If-elif-else Statement Example

In addition to else-if, we can check for new conditions, if the program goes to else block.

bash if else if example

The elif (else if) is used for multiple if conditions. In case one if the condition goes false then check another if conditions. For example, input the marks of a student and check if marks are greater or equal to 80 then print “Very Good”. If marks are less than 80 and greater or equal to 50 then print 50 and so on. Check the below script and execute it on the shell with different-2 inputs.

4. Bash – Nested if Statement Example

With nested if one condition goes true then only check another condition. For example, take 3 numeric values as input and check the greatest value.

Tags , ,
Was this article helpful to you? Yes 31 No 10
Advertisement