if [ "$1" = 'y' -a $2 -gt 0 ]; then
echo "yes"
fi
if [ "$1" = 'n' -o $2 -lt 0 ]; then
echo "no"
fi
Bash Conditionals
logical and, or
More conditions
Condition | Description |
---|---|
[[ -o noclobber ]] |
If OPTION is enabled |
[[ ! EXPR ]] |
Not |
[[ X && Y ]] |
And |
[[ X || Y ]] |
Or |
File conditions
Condition | Description |
---|---|
[[ -e FILE ]] |
Exists |
[[ -d FILE ]] |
Directory |
[[ -f FILE ]] |
File |
[[ -h FILE ]] |
Symlink |
[[ -s FILE ]] |
Size is > 0 bytes |
[[ -r FILE ]] |
Readable |
[[ -w FILE ]] |
Writable |
[[ -x FILE ]] |
Executable |
[[ f1 -nt f2 ]] |
f1 newer than f2 |
[[ f1 -ot f2 ]] |
f2 older than f1 |
[[ f1 -ef f2 ]] |
Same files |
Example
#String
if [[ -z "$string" ]]; then
echo "String is empty"
elif [[ -n "$string" ]]; then
echo "String is not empty"
else
echo "This never happens"
fi
#Combinations
if [[ X && Y ]]; then
...
fi
#Equal
if [[ "$A" == "$B" ]]; then
...
fi
#Regex
if [[ '1. abc' =~ ([a-z]+) ]]; then
echo ${BASH\_REMATCH[1]}
fi
#Smaller
if (( $a < $b )); then
echo "$a is smaller than $b"
fi
#Exists
if [[ -e "file.txt" ]]; then
echo "file exists"
fi
String conditions
Condition | Description |
---|---|
[[ -z STR ]] |
Empty string |
[[ -n STR ]] |
Not empty string |
[[ STR == STR ]] |
Equal |
[[ STR = STR ]] |
Equal (Same above) |
[[ STR < STR ]] |
Less than (ASCII) |
[[ STR > STR ]] |
Greater than (ASCII) |
[[ STR != STR ]] |
Not Equal |
[[ STR =~ STR ]] |
Regexp |
Integer conditions
Condition | Description |
---|---|
[[ NUM -eq NUM ]] |
Equal |
[[ NUM -ne NUM ]] |
Not equal |
[[ NUM -lt NUM ]] |
Less than |
[[ NUM -le NUM ]] |
Less than or equal |
[[ NUM -gt NUM ]] |
Greater than |
[[ NUM -ge NUM ]] |
Greater than or equal |
(( NUM < NUM )) |
Less than |
(( NUM <= NUM )) |
Less than or equal |
(( NUM > NUM )) |
Greater than |
(( NUM >= NUM )) |
Greater than or equal |
Comments