We are going to see if statement in bash shell scripting in Linux/UNIX environment.
If statement is playing the most important role in bash shell scripting and other programming languages. Its working based on condition and we can write another if statement inside of an if statement.
Syntax of If statement:
if [ condition..] then < commands...> else < commands... > fi
Basic if statement says that, if a condition if valid then, it will execute the single/ set of commands which is comes under then will execute and if a condition not valid then, it will execute the single/ set of commands which comes under else. Finally, it will be ended.
We have some operator which is useful in if statement conditions for validation. Below they are.
Operator | Description |
---|---|
=, ==, -eq | This is to check string/numeric value is equal to another string/ numeric value. |
!=,-ne | This is to check string/numeric value is not equal to another string/ numeric value. |
<=, -le | This is to check string/numeric value is less than or equal to another string/ numeric value. |
>=, -ge | This is to check string/numeric value is greater than or equal to another string/ numeric value. |
<, -lt | This is to check string/numeric value is less than to another string/ numeric value. |
>, -gt | This is to check string/numeric value is greater than to another string/ numeric value. |
Example:
[root@server ~]# vi newscript.sh #!/bin/bash if [[ $1 -gt "100" ]] then echo "Given values is greater than 100.." else echo "Given value is equal to or less than 100..." fi
Then provide the execute permission to the script using chmod command.
[root@server ~]# chmod +x newscript.sh
Now will run the script by passing a parameter
[root@server ~]# ./newscript.sh 101 Given values is greater than 100..