The 3 forms Of If Statement In Bash

Pavol Kutaj
1 min readNov 20, 2021

--

The aim of this page📝is to define the syntax and conventions of if statements in Bash.

1. notes

  • bash IF statements are wordy (compared to posh/python) — look at its syntax
if <TEST>; then
<PASSED_CODE>
elif <TEST>; then
<PASSED_CODE>
else
<FAILED_CODE>
fi
  • tradition dictates that then is on the same line with if
  • if it is, it also must be separated from if with ;
  • but it is not always like this in the wild, then can be found on a new line, too
  • you could put the whole block on a single line, separating if, elif, else and fi with ;

2. singleline shell form

  • create games folder from the shell, write ok if succeeds, write error when fails
  • note required ; separator between statements
>>> if mkdir games; then echo "ok"; else echo "error"; fi;

3. traditional form

  • minimalistic check for the presence of an argument with a conditional expression
if [[ ! $1 ]]; then
echo "Missing Argument"
exit 1
fi

4. nonconventional form

  • each statement is on a new line
  • there is no ;
if [[ $size_mb -gt 0 ]]
then
log "Size of files: $size_mb MB"
elif [[ $size_kb -gt 0 ]]
then
log "Size of files: $size_kb KB"
else
log "Size of files: $size_bytes bytes"
fi

--

--

Responses (1)