Conditional Statements
Here's an example of a shell script that demonstrates conditional statements:
#!/bin/bash
# Get user input
echo "Enter a number:"
read number
# Conditional statements
if [ "$number" -gt 0 ]; then
echo "The number is positive."
elif [ "$number" -lt 0 ]; then
echo "The number is negative."
else
echo "The number is zero."
fi
In this script, we have the following conditional statement-related operations:
Get User Input: We use the
read
command to prompt the user to enter a number, and store the input in thenumber
variable.Conditional Statements: We use the
if
,elif
, andelse
keywords to create conditional blocks. Inside the blocks, we use square brackets[ ]
to enclose the conditions. In this example, we check if the number is greater than zero ("$number" -gt 0
), less than zero ("$number" -lt 0
), or equal to zero (default case). Depending on the condition that evaluates to true, the corresponding message is printed.elif
(Else If): If the first condition is false, the script checks the next condition usingelif
. You can have multipleelif
blocks to test additional conditions.else
: If none of the previous conditions are true, theelse
block is executed.
When you run the script, it prompts you to enter a number. Based on the number entered, it evaluates the conditions and displays the appropriate message indicating whether the number is positive, negative, or zero.
For example, if you enter 10
, the output will be:
The number is positive.
If you enter -5
, the output will be:
The number is negative.
And if you enter 0
, the output will be:
The number is zero.
You can customize and expand this script by adding more conditions, nested if-else statements, and additional actions based on the conditions. Conditional statements allow you to make decisions and control the flow of execution in your shell scripts based on specific conditions.
Last updated