if
if
The if statement in Unix-like operating systems is a fundamental control structure used in shell scripting to perform conditional execution of commands. It allows you to execute a set of commands only if a specified condition is true, and optionally execute another set of commands if the condition is false.
Basic Syntax
if condition
then
commands
ficondition: A command or test expression that returns a true (0) or false (non-zero) exit status.
commands: The commands to execute if the condition is true.
Extended Syntax
You can extend the if statement with else and elif (else if) clauses to handle multiple conditions:
if condition1
then
commands1
elif condition2
then
commands2
else
commands3
ficondition1: The primary condition to test.
commands1: Commands to execute if condition1 is true.
condition2: The secondary condition to test if condition1 is false.
commands2: Commands to execute if condition2 is true.
commands3: Commands to execute if neither condition1 nor condition2 is true.
Examples
Basic if Statement
if-else Statement
if-elif-else Statement
Practical Use Cases
Checking File Existence
Checking Directory Existence
Comparing Numbers
Checking Command Exit Status
Advanced Examples
Nested if Statements
Combining Conditions with && and ||
Using test Command
test CommandThe test command (or its alias [ ... ]) is used to evaluate expressions:
Conclusion
The if statement is a crucial tool in shell scripting, enabling conditional execution of commands based on the evaluation of expressions. By using if, else, and elif clauses, you can create scripts that respond dynamically to different conditions and states.
help
Last updated