Bash structured language constructs
You can use the if command to test a condition. For example, shell script may need to execute tar command only if a certain condition exists (such as backup only on Friday night).
If today is Friday execute tar command otherwise print an error message on screen.
More About Logic
- So far, the script you've used followed sequential flow:
#!/bin/bash echo "Today is $(date)" echo "Current directory : $PWD" echo "What Users Are Doing:" w
- Each command and/or statement is executed once, in order in above script.
- With sequential flow scripts, you cannot write complex applications (intelligent Linux scripts).
- However, with if command you will be able to selectively run certain commands (or part) of your script.
- You can create a warning message and run script more interactively using if command to execute code based on a condition.
But What Is A Condition?
- A condition is nothing but an expression that evaluates to a boolean value (true or false).
- In other words condition can be either true or false.
- A condition is used in shell script loops and if statements.
So, How Do I Make One?
A condition is mainly a comparison between two values. Open a shell prompt (console) and type the following command:
echo $(( 5 + 2 ))
Addition is 7. But,
echo $(( 5 < 2 ))
Answer is zero (0). Shell simple compared two number and returned result as true or false. Is 5 is less than 2? No. So 0 is returned. The Boolean (logical data) type is a primitive data type having one of two values
- 0 value indicates false.
- 1 or non-zero value indicate true.
|Operator||Example||Description||True / False||Evaluates To|
|5 > 12||echo $(( 5 > 12 ))||Is 5 greater than 12?||No (false)||0|
|5 == 10||echo $(( 5 == 10 ))||Is 5 equal to 10?||No (false)||0|
|5 != 2||echo $(( 5 != 2 ))||5 is not equal to 2?||Yes (true)||1|
|1 < 2||echo $(( 1 < 2 ))||Is 1 less than 2?||Yes (true)||1|
|5 == 5||echo $(( 5 == 5 ))||Is 5 equal to 5?||Yes (true)||1|
Now, it makes no sense to use echo command for comparisons. But, when you compare it with some value it becomes very useful. For example:
if [ file exists /etc/resolv.conf ] then make a copy else print an error on screen fi