Book Image

Linux Shell Scripting Essentials

By : Sinny Kumari, Khem Raj
Book Image

Linux Shell Scripting Essentials

By: Sinny Kumari, Khem Raj

Overview of this book

Table of Contents (15 chapters)
Linux Shell Scripting Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 executed.

The syntax of if and else is as follows:

if [ conditional_expression ]
then
  statements
else
  statements
fi

Sometimes, when a condition is not true, we might want to execute some statements. In such cases, use if and else. Here, if conditional_statement...