Bash Scripting – Compound Testing
- [ condition1 ] && [ condition2 ]
- [ condition1 ] || [ condition2 ]
The following shows the AND Boolean operator in use:
$ cat test22.sh #!/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 cannot write to the file” fi $ $ ./test22.sh I cannot write to the file $ $ touch $HOME/testing $ $ ./test22.sh 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.