Conditionally execute code (use of: if, test, [], etc.)
Context: RHCSA exam commands examples
Create simple shell scripts
[ ] Conditionally execute code (use of: if, test, [], etc.)
Certainly! Here are some examples of shell commands and scripts that demonstrate conditional execution using the if
, test
, and []
constructs:
- Simple if statement:
if [ condition ]; then
# code to execute if condition is true
fi
Example:
if [ $1 -gt 10 ]; then
echo "The number is greater than 10."
fi
This script takes a number as an argument and checks if it is greater than 10. If it is, it prints a message.
- If-else statement:
if [ condition ]; then
# code to execute if condition is true
else
# code to execute if condition is false
fi
Example:
if [ $1 -eq 0 ]; then
echo "The number is zero."
else echo "The number is not zero."
fi
This script takes a number as an argument and checks if it is zero. If it is, it prints a specific message; otherwise, it prints a different message.
- If-elif-else statement:
if [ condition1 ]; then
# code to execute if condition1 is true
elif [ condition2 ]; then
# code to execute if condition2 is true
else
# code to execute if all conditions are false
fi
Example:
if [ $1 -gt 0 ]; then
echo "The number is positive."
elif [ $1 -lt 0 ];
then echo "The number is negative."
else echo "The number is zero."
fi
This script takes a number as an argument and checks if it is positive, negative, or zero, printing the corresponding message.
These examples demonstrate the basic structure of conditional execution in shell scripting. You can replace the condition
in square brackets with any valid shell condition, such as logical operators (-a
, -o
), file tests (-f
, -d
), string comparisons (==
, !=
), and more.