Bash Howto If statement

How do I use If ... else statement in bash

  1. Statement in
  2. Instruction in
  3. Instruction in
  4. Nested statement in

Conditional statements are widely used for decision making in almost all programming languages. They only allow one or more statements to be executed if a certain condition is met. used as a conditional statement in most programming languages. In we also have,, and nested statements as conditional statements.

Statement in

Statement syntax

If it is in the example above, they will be executed. The keyword is used to end the statement.

If it is not, then none of the instructions will be executed.

To make our code look more readable and organized, we can either use an indentation with or.

Example: statement in

Output:

It accepts a number from the user and only outputs output if the number is even.

If the number is even, the remainder is zero when the number is divided by two. Hence, the is such that the statement is executed.

Instruction in

Statement syntax

If it is in this example, then the will be executed; otherwise the will be executed. The keyword is used to end the statement.

Example: statement in

Output:

It accepts a number from the user and outputs an output based on whether the entered number is exactly divisible by or not.

If the number is even, the remainder is zero when the number is divided by two; therefore is the test expression and the statement is executed.

If the number is odd, the remainder is not zero; therefore is the test expression and the statement is executed.

Instruction in

Statement syntax

If that is the case, it will be carried out. Otherwise, if it is, it will be executed.

If neither of the two test expressions is true, the will be executed.

We can have as many statements as we want, and the statement is optional.

Example: statement in

Output:

It takes two numbers as input from the user and outputs the result based on which of the test expressions is true.

If so, the program reports that is.

If so, the program prints.

If neither of the two conditional statements is true, the program prints.

Nested statement in

When one statement is inserted into another statement, it is called a nested statement.

Output:

It demonstrates the use of the nested statement. If the number is exactly divisible by and greater than, the statement is executed.