Bash Scripting Logical Operators

  1. AND: &&

Run the second command only if the first succeeds:

mkdir mydir && cd mydir
git pull && echo "Pull successful"
  1. OR: ||

Run the second command only if the first fails:

cd mydir || mkdir mydir
command -v docker &>/dev/null || sudo apt install docker
  1. 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!"
  1. 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.”

  1. Syntax Rules
# Spaces are required around brackets and operators
[[ "$name" == "DevOps" ]]
# CORRECT
[[  "$name"=="DevOps"  ]]
# WRONG - no spaces around ==
  1. 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"

my DevOps Odyssey

“Σα βγεις στον πηγαιμό για την Ιθάκη, να εύχεσαι να ‘ναι μακρύς ο δρόμος, γεμάτος περιπέτειες, γεμάτος γνώσεις.” - Kavafis’ Ithaka.



2026-03-13

Series:lab

Categories:Linux

Tags:#bash, #linux, #scripts, #lab


Bash Scripting Logical Operators: