Here are some examples of using the if
command for conditional scripting in KSH (Korn Shell):
if [ condition ]; then commands fi
The condition
is a Boolean expression that is evaluated as either true
or false
. If the condition
is true
, the commands
will be executed.
Here is an example of an if
statement that checks if a variable is equal to a string:
my_var="apple" if [ "$my_var" = "apple" ]; then echo "The variable is equal to 'apple'" fi
if [ condition ]; then commands1 else commands2 fi
If the condition
is true
, the commands1
will be executed. If the condition
is false
, the commands2
will be executed.
Here is an example of an if-else
statement that checks if a variable is equal to a string:
my_var="apple" if [ "$my_var" = "apple" ]; then echo "The variable is equal to 'apple'" else echo "The variable is not equal to 'apple'" fi
if [ condition1 ]; then commands1 elif [ condition2 ]; then commands2 else commands3 fi
The if-elif-else
statement allows you to specify multiple conditions and sets of commands. If condition1
is true
, commands1
will be executed. If condition1
is false
and condition2
is true
, commands2
will be executed. If both condition1
and condition2
are false
, commands3
will be executed.