Compound Condition Testing - Shell Scripting

The if-then statement allows you to use Boolean logic to combine tests. There are two Boolean operators you can use: [ condition1 ] && [ condition2 ] [ condition1 ] || [ condition2 ] The first Boolean operation uses the AND Boolean operator to combine two conditions. Both conditions must be met for the then section to execute. The second Boolean operation uses the OR Boolean operator to combine two conditions. If either condition evaluates to a true condition, the then section is executed. $ cat test22 #!/bin/bash # testing compound comparisons if [ -d $HOME ] && [ -w $HOME/testing ] then echo "The file exists and you can write to it" else echo "I can’t write to the file" fi $ ./test22 I can’t write to the file $ touch $HOME/testing $ ./test22 The file exists and you can write to it $ Using the AND Boolean operator, both of the comparisons must be met. The first comparison checks to see if the HOME directory exists for the user. The second comparison checks to see if there’s a file called testing in the user’s HOME directory, and if the user has write permissions for the file. If either of these comparisons fails, the if statement fails and the shell executes the else section. If both of the comparisons succeed, the if statement succeeds and the shell executes the then section.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Shell Scripting Topics