Explaining Bash If Statements Without Square Brackets

Pavol Kutaj
1 min readMar 6, 2024

--

  • Usually, you encounter if statements followed by [ (aka test command) or [[ (aka conditional expression) in bash.
  • Not always! Why?
  • In bash, when using the if statement without square brackets, the condition that follows can be any command or pipeline of commands. The if statement evaluates the exit status of the command(s) to determine whether to execute the consequent or alternative block.
  • What is being tested is only the exit status of the command(s) — not the values of variables!
  • It seems to me that in this particular regard, Bash has the concept of truthy/falsy that it otherwise lacks (for more, see https://github.com/Jeff-Russ/bash-boolean-helpers?tab=readme-ov-file#why)
  • If the command(s) return an exit status of 0 (which indicates success), the then block will be executed.
  • If the command(s) returns a non-zero exit status (indicating failure), the else the block will be executed.

4 types of usage:

1. Single command

if command; then
# do something
else
# do something else

2. Pipeline of commands

if command1 | command2; then
# do something
else
# do something else
fi

3. Command substitution

if $(some_command); then
# do something
else
# do something else
fi

4. Function call

if my_function; then
# do something
else
# do something else
fi

So, in summary, when using the if statement without square brackets in bash, you can follow it with any valid command or combination of commands.

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com