Bash Logical Operators
Logical operators join tests or flip a test result. They let one if statement check several facts at once.
Both Must Pass
The operator && joins two separate tests. Both tests pass here, so the line prints.
ready="yes"
invited="yes"
if [ "$ready" = "yes" ] && [ "$invited" = "yes" ]; then
echo "You can enter"
fiOne Must Pass
The operator || joins two separate tests. The first test passes, and that is enough.
day="Saturday"
if [ "$day" = "Saturday" ] || [ "$day" = "Sunday" ]; then
echo "It is the weekend"
fiFlipping a Test
The mark ! stands before the brackets. It flips the result, so a false test acts true.
answer="no"
if ! [ "$answer" = "yes" ]; then
echo "The answer is not yes"
fiExample
age=25
member="yes"
weekday="Monday"
locked="no"
if [ "$age" -ge 18 ] && [ "$member" = "yes" ]; then
echo "An adult member can book"
fi
if [ "$weekday" = "Monday" ] || [ "$weekday" = "Friday" ]; then
echo "Booking opens today"
fi
if ! [ "$locked" = "yes" ]; then
echo "The door is not locked"
fiKey points
- The operator && needs both tests to pass.
- The operator || needs only one test to pass.
- The mark ! flips a test result.
- Each test keeps its own square brackets.
- A flipped true test becomes false.
- Joined tests run from left to right.
In this example, all three operators check one booking. The && test needs both facts, the || test needs one day, and ! flips the lock test.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which operator needs both joined tests to pass?