- AND: &&
Run the second command only if the first succeeds:
mkdir mydir && cd mydir
git pull && echo "Pull successful"
- OR: ||
Run the second command only if the first fails:
cd mydir || mkdir mydir
command -v docker &>/dev/null || sudo apt install docker
- Chaining
&& and || are your bread and butter. They check exit codes.
This is why exit codes matter - they drive conditional execution.
cd project || mkdir project && cd project
./run-tests && ./deploy || echo "Tests failed!"
- The [[]] Test command - Security Critical
“Single brackets are a security vulnerability. Double brackets. Always. No exceptions.”*
Always use [[ ]], NEVER single brackets [ ]:
# WRONG - single brackets have many gotchas
if [ $name == "DevOps" ]; then
# CORRECT - double brackets are safer
if [[ "$name" == "DevOps" ]]; then
Why Single Brackets Are Dangerous
Single brackets [ ] are an external binary (/usr/bin/[). They don’t prevent word splitting.
name="hello world"
# Single brackets - BREAKS!
[ $name == "hello world" ]
# ERROR: too many arguments
# Double brackets - works
[[ $name == "hello world" ]]
# No error
“I’ve seen production outages caused by single brackets and unquoted variables. This isn’t academic - it’s job security.”
- Syntax Rules
# Spaces are required around brackets and operators
[[ "$name" == "DevOps" ]]
# CORRECT
[[ "$name"=="DevOps" ]]
# WRONG - no spaces around ==
- String Comparisons
str1="hello"
str2="world"
[[ "$str1" == "$str2" ]] && echo "Equal"
[[ "$str1" != "$str2" ]] && echo "Not equal"
# Empty/not empty
[[ -z "$name" ]] && echo "Empty"
[[ -n "$name" ]] && echo "Not empty"