Introduction
Logical operators help you combine or reverse conditions in scripts to make decisions.
if [ condition1 -a condition2 ]; then # commands fi if [ condition1 -o condition2 ]; then # commands fi if [ ! condition ]; then # commands fi
if [ -f file1.txt -a -f file2.txt ]; then echo "Both files exist" fi
if [ -d /tmp -o -d /var ]; then echo "At least one directory exists" fi
if [ ! -f missing.txt ]; then echo "missing.txt does not exist" fi
#!/bin/bash file1="file1.txt" file2="file2.txt" # Create only file1.txt for this example touch "$file1" if [ -f "$file1" -a -f "$file2" ]; then echo "Both files exist" elif [ -f "$file1" -o -f "$file2" ]; then echo "Only one file exists" else echo "No files exist" fi if [ ! -f "$file2" ]; then echo "$file2 does not exist" fi
[ ]?-a means AND, -o means OR, and ! means NOT.-a is used to combine two conditions with AND logic.file.txt exists AND is readable in bash?file.txt exists AND is readable, so both conditions must be true.-a means AND, so [ -e file.txt -a -r file.txt ] is correct. Using -o means OR, which is wrong here. Using && inside [ ] is invalid syntax.if [ -f myfile.txt -o ! -r myfile.txt ]; then echo "Check passed"; else echo "Check failed"; fi
myfile.txt exists but is NOT readable.-f myfile.txt is true because file exists. ! -r myfile.txt is true because file is not readable.if [ !-f myfile.txt -a -r myfile.txt ]; then echo "Valid"; fi
! must have a space after it inside [ ]. The code [ ! -f myfile.txt -a -r myfile.txt ] is correct only if spaces are present. If missing, it causes error.-a inside [ ] is valid. The closing bracket is present. So no error there.var is NOT empty AND file1.txt exists OR file2.txt is readable. Which condition is correct?Pass the test and this pattern moves unknown