Rabi Siddique
217 words
1 minutes
Conditionals in Bash Scripting
2024-07-08

Conditionals in Bash let you make decisions in your scripts, directing the flow of execution depending on whether certain conditions are true or not. The main types of conditional statements in Bash are if, else, and elif.

So here it how it works:

if [ condition ]
then
  # Commands to execute if the condition is true
elif [ another_condition ]
then
  # Commands to execute if the first condition is false and the second condition is true
else
  # Commands to execute if all the conditions above are false
fi

In this syntax, the square brackets [ ] represent the test command in Bash, which checks the condition inside them. It’s important to leave a space after the opening bracket and before the closing bracket.

Common Conditions You Might Check:#

Numeric comparisons#

  • -eq: equals
  • -ne: not equal
  • -lt: less than
  • -le: less than or equal to
  • -gt: greater than
  • -ge: greater than or equal to

String comparisons#

  • =: equals
  • !=: not equal
  • -z: string is null (empty)
  • -n: string is not null (not empty)
  • A good read over here

File attributes#

  • -e: exists
  • -f: is a file
  • -d: is a directory
  • -r: is readable
  • -w: is writable
  • -x: is executable

In Bash, a condition that results in 0 (zero) is considered true, which might seem unusual because, in many other contexts, zero can imply false. Conversely, any non-zero result is treated as false.

A good link to read more conditionals in Bash.

Conditionals in Bash Scripting
https://rabisiddique.com/posts/bash-scripting-conditionals/
Author
Rabi Siddique
Published at
2024-07-08