programming-languages:bash:test
Table of Contents
Tests
Expressions are tested whether they are True
or False
using the if
statement.
#!/bin/bash x=0 if [[ ! $x ]]; then echo "empty value" elif [[ $x =~ [a-zA-Z] ]]; then echo "$x not an integer" else if [[ $x -gt 0 ]]; then echo "$x > 0" elif [[ $x -lt 0 ]]; then echo " $x < 0" elif [[ $x -eq 0 ]]; then echo "$x == 0" fi fi
Info: the operator =~
allows to use of a regular expression in the test.
Otherwise, expressions are tested whether they have a specific value using the case
statement.
#!/bin/bash x=0 case $x in "") echo "empty value" ;; 0) echo "$x == 0" ;; *) echo "unknown value" ;; esac
Info: alternative patterns can be checked with the |
operator: a|b) echo “$x == a or $x == b”
.
Logical operators
Operation | Operator |
---|---|
and | && |
or | || |
not | ! |
File expressions
Expression | True if |
---|---|
-e <file> | <file> exists |
-d <file> | <file> exists and is a directory |
-s <file> | <file> exists and has a length greater than zero |
-r <file> | <file> exists and is readable |
-w <file> | <file> exists and is writable |
-x <file> | <file> exists and is executable |
String expressions
Expression | True if |
---|---|
<str> | <str> is not null |
-n <str> | <str> length is greater than zero |
-z <str> | <str> length is zero |
<str1> == <str2> | <str1> and <str2> are equal |
<str1> != <str2> | <str1> and <str2> are not equal |
<str1> > <str2> | <str1> comes after <str2> in lexicographically order |
<str1> < <str2> | <str1> comes before <str2> in lexicographically order |
Integer expressions
Expression | True if |
---|---|
<int1> -eq <int2> | <int1> is equal to <int2> |
<int1> -ne <int2> | <int1> is not equal to <int2> |
<int1> -le <int2> | <int1> is less than or equal to <int2> |
<int1> -lt <int2> | <int1> is less than <int2> |
<int1> -ge <int2> | <int1> is greater than or equal to <int2> |
<int1> -gt <int2> | <int1> is greater than <int2> |
programming-languages/bash/test.txt · Last modified: 2023/11/04 12:12 by tormec