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

54 lines
921 B
Markdown
Raw Normal View History

# conditions.
## boolean check.
```bash
local predicate=true # or false.
if $predicate; then
# if true.
else
# if false.
fi
```
## variables comparison.
```bash
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.
```bash
local var1=true
if ! $var1; then ...
if [[ ! -f test.txt ]]; then ...
```
## check if file exists.
```bash
if [[ -f file.txt ]]; then ...
```