Logical Operators
In this page:
&& for Sequential Success
&& runs the command on its right only if the command on its left exited with status 0. This is a compact way to chain steps that should only proceed if the previous one worked, without writing a full if block.
Example: && for Sequential Success
#!/bin/bash
mkdir -p output_dir && echo "Directory ready, continuing"
cd output_dir && echo "Now inside output_dir: $(pwd)"
Login to try C/C++/Java/PHP code in the editor
|| for Fallback on Failure
|| runs the command on its right only if the command on its left exited with a non-zero status. This is commonly used to provide a fallback action or error message when something fails.
Example: || for Fallback on Failure
#!/bin/bash
grep -q "xyz" <<< "abc def" || echo "Pattern 'xyz' was not found, using fallback"
Login to try C/C++/Java/PHP code in the editor
! to Negate a Condition
! inverts the exit status of the command or test immediately following it, turning success into failure and failure into success. Inside [ ] or [[ ]], it is placed directly before the condition being negated.
Example: ! to Negate a Condition
#!/bin/bash
if [ ! -f nonexistent_file.txt ]; then
echo "Confirmed: nonexistent_file.txt does not exist"
fi
if ! grep -q "zzz" <<< "hello world"; then
echo "Confirmed: pattern not found"
fi
Login to try C/C++/Java/PHP code in the editor
Combining && and || Together
&& and || can be chained on one line for a compact 'if success do X, else do Y' pattern, evaluated strictly left to right. Be careful with more complex combinations -- for anything beyond a simple two-way branch, a proper if/else is clearer and less error-prone.
Warning: If the middle command in an &&/|| chain can itself fail for reasons unrelated to the condition, the || fallback might run unexpectedly -- prefer if/else when the logic gets complex.
Example: Combining && and || Together
#!/bin/bash
value=10
[ "$value" -gt 5 ] && echo "Value is greater than 5" || echo "Value is 5 or less"
Login to try C/C++/Java/PHP code in the editor
- Thinking
&&/||operate on true/false booleans; they actually chain based on a command's exit status (0 = success), socommand1 && command2really means 'run command2 only if command1 exited 0'. - Misplacing
!when negating inside[ ]vs[[ ]];!needs to go right before the expression ([ ! -f file ]), not before the wholeif. - Chaining many
&&/||together without parentheses/grouping and being surprised by the result, since&&and||are evaluated left to right with equal precedence, unlike in some other languages.
cmd1 && cmd2runscmd2only ifcmd1exited with status 0 (succeeded).cmd1 || cmd2runscmd2only ifcmd1exited with a non-zero status (failed).!negates the exit status of the command or test that follows it -- success becomes failure and vice versa.- Inside
[[ ]],&&and||combine sub-conditions directly; outside of[[ ]]/(( )), they combine whole commands.
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: