if-else conditional statements
In shell scripting, if-else
conditions allow you to execute different blocks of code based on certain conditions. The syntax for an if-else
statement in shell scripting is as follows:
Syntax:
if condition
then
# code to be executed if condition is true
else
# code to be executed if condition is false
fi
Here’s a breakdown of how if-else
conditions work:
if
statement: This is the starting point of the conditional block. It checks a specific condition.then
keyword: This marks the beginning of the code block that will be executed if the condition is true.- Code Block: The commands or code you want to execute if the condition evaluates to true. This can be a single command or a series of commands.
else
statement: If the condition in theif
statement is false, the code after theelse
keyword is executed.fi
statement: This marks the end of theif-else
block.
Here’s an example to illustrate the usage of if-else
in a shell script:
#!/bin/bash
# Prompting user for input
read -p "Enter a number: " num
if [ $num -gt 0 ]
then
echo "The number is positive."
else
echo "The number is non-positive."
fi
In this example, the script prompts the user to enter a number. It then checks if the number is greater than zero. If it is, it prints “The number is positive.” Otherwise, it prints “The number is non-positive.”
Keep in mind the following important points:
- Use
[ ]
to denote the condition. The spaces around the square brackets are important. - Ensure there’s a space after
if
,then
,else
, and beforefi
. - The condition can be any valid shell expression, and it’s evaluated within the
[ ]
.
You can also have multiple conditions using elif
(short for “else if”) statements:
Syntax:
if condition1
then
# code for condition1 being true
elif condition2
then
# code for condition2 being true
else
# code for all conditions being false
fi
This allows you to check multiple conditions in sequence. The first condition that evaluates to true will execute its corresponding block of code. If none are true, the else
block will execute.