O'Reilly logo

Linux Shell Scripting Essentials by Sinny Kumari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using conditional statements with if and else

Shell provides if and else to run conditional statements depending upon whether the evaluation is true or false. It is useful if we want to perform certain tasks only if a certain condition is true.

The test condition to if can be given using a test condition or [condition]. We have already learned multiple use cases and examples of testing an expression in the previous section, Testing expressions with a test.

Simple if and else

The syntax of the if condition is as follows:

if [ conditional_expression ]
then
  statements
fi

If conditional_expression is true—that is, the exit status is 0—then the statements inside it get executed. If not, then it will be just be ignored and the next line after fi will be ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required