if statements
If statements are conditional statements used to test whether the condition is true or false and then continue executing the script.
if statements in Linux Shell Scripting
if condition
Syntax:
if condition then execute some commands ... ... fi
Example: if.sh
# SOME VARIABLES x=7 # TESTING... if [ $x -eq 7 ] then { echo "$x is equal to 7!" } fi
In the above example if condition was used to check if the value of x is equal to 7.
If the condition is true it will print the result.
If else condition
Syntax:
if condition then condition is true execute some commands else if condition is not true execute some commands up fi
Example: if-else.sh
# Get the value from the user echo " Enter a value for the variable x:" read x # TESTING the value of x is 7 or not! if [ $x -eq 7 ] then { echo "$x is equal to 7!" } else { echo "$x is not equal to 7!" } fi
running the script: if-else.sh
sh if-else.sh
Enter a value for the variable x:
3
3 is not equal to 7!
In the above example, based on the value of x given by you, the script will determine if the value of x is 7 or not.
Nested If else condition
Syntax:
if condition then if condition then ..... .. do this else .... .. do this fi else ... ..... do this fi
Example: nested-if-else.sh
# Get the value from the user echo " Enter a value for the variable x:" read x # TESTING the value of x is 0 or not! if [ $x -eq 0 ] then { echo "$x is equal to 0!" } else { if [ $x -gt 0 ] then { echo "$x is greater than 0!" } else { echo "$x is less than 0!" } fi } fi
running the script: nested-if-else.sh
./nested-if-else.sh
Enter a value for the variable x:
-10
-10 is less than 0!
Here the script can determine the value entered by you is less than 0 , greater than 0 or equal to 0. Try running this script with different values.
Related posts:
- Shell Scripting Introduction
- Shell Syntax
- Shell - Strings
- Shell - Variables
- Shell - User Intraction
- First Shell Script
- Shell - Arithmetics
- Shell - Case Statement
- Shell - Command Line Arguments
- Shell - For Loop
- Shell - While Loops
- Shell - IF Statements
- Shell - Input Output Redirections
- Shell - Pipes and Filters
- Shell - Process Management
Your IP address1 is: 172.18.0.2
Tutorials
Latest Updates
Follow us
- Tech-Tutorials twitter.com/techcuriosity