0
0
Bash Scriptingscripting~5 mins

Logical operators (-a, -o, !) in Bash Scripting

Choose your learning style9 modes available
Introduction
Logical operators help you combine or reverse conditions in scripts to make decisions.
Check if two files both exist before running a command.
Run a command if either one of two conditions is true.
Skip a step if a certain condition is not met.
Combine multiple checks in an if statement for better control.
Syntax
Bash Scripting
if [ condition1 -a condition2 ]; then
  # commands
fi

if [ condition1 -o condition2 ]; then
  # commands
fi

if [ ! condition ]; then
  # commands
fi
Use -a for AND (both conditions must be true).
Use -o for OR (at least one condition must be true).
Use ! to negate (reverse) a condition.
Examples
Checks if both file1.txt and file2.txt exist.
Bash Scripting
if [ -f file1.txt -a -f file2.txt ]; then
  echo "Both files exist"
fi
Checks if either /tmp or /var directory exists.
Bash Scripting
if [ -d /tmp -o -d /var ]; then
  echo "At least one directory exists"
fi
Checks if missing.txt does NOT exist.
Bash Scripting
if [ ! -f missing.txt ]; then
  echo "missing.txt does not exist"
fi
Sample Program
This script checks if two files exist using logical operators. It creates file1.txt only, then tests conditions with -a, -o, and !.
Bash Scripting
#!/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
OutputSuccess
Important Notes
Always put spaces around [ and ] and between conditions and operators.
For complex conditions, consider using [[ ... ]] with && and || for better readability.
Logical operators inside [ ] are less flexible than in [[ ]], but still widely used.
Summary
Logical operators combine conditions to control script flow.
-a means AND, -o means OR, and ! means NOT.
Use them inside [ ] to test multiple conditions simply.