wiki/help/linux/bash/script/condition.md

921 B

conditions.

boolean check.

local predicate=true # or false.

if $predicate; then
  # if true.
else
  # if false.
fi

variables comparison.

local var1="test"
local var2="test"

if [[ "$var1" = "$var2" || "$var1" != "$var2" ]]; then
  # if equal or not equal.
fi

if [[ "$var1" =~ "[Tt]est" ]]; then
  # if matches regex.
fi

if [[ "$var1" > "$var2" || "$var1" < "$var2" ]]; then
  # string comparison (lexographical).
fi

if [[ -z "$var1" || "$var1" = "" ]]; then
  # if variable is empty
fi

if [[ -n "$var1" || "$var1" != "" ]]; then
  # if variable not empty.
fi

please note that spaces inside [[ ... ]] are required (because [ and ] are actually operators).

negation.

add ! before condition. space before and after required.

local var1=true

if ! $var1; then ...
if [[ ! -f test.txt ]]; then ...

check if file exists.

if [[ -f file.txt ]]; then ...