Operators
Arithmetic
Bash does not know how to add, reduce, multiply... 2 solutions:
Create variables:
var=$((number operation number)); echo $var
test=$((50*50)); echo $test
Command 'bc':
apt install bc
echo "number operation number" | bc
echo "50*50" | bc
Comparison
0 = TRUE
1 = FALSE
Numbers:
-eq
is equal
-ne
is not equal
Numbers:
-gt
is greater
-ge
is greater or equal
Numbers:
-lt
is lower
-le
is lower or equal
Text:
=
is equal
!=
is not equal
Text:
\>
is greater
Text:
\<
is lower
Commands to use:
test
,[
,[[
var1=100 var2=101 test $var1 -eq $var2
//[ $var1 -eq $var2] echo $?
result will be 1 -> falsevar1="hello" var2="goodbye" test "$var1" != "$var2" echo $?
result will be 0 -> true
Find substring
var1="ImaWildSubstring, can you find me?" [[ "$var1" == *"WildSubstring"* ]] echo $?
result will be 0 -> true
#!/bin/bash
fileToUse=$1
wordToFind=$2
text=$(cat $fileToUse)
[[ "$text" == *$wordToFind* ]]
echo $?
Logic
&&
and
||
or
!
false
v1=20 v2=30 v3=40 v4=50 test $v1 -ne $v2 && test $v3 -gt $v4 echo $?
result will be 0 -> true
File test existence
Commands to use: test
, [
, [[
-e
checks if file exists.-f
checks if file exists and it is regular.Regular would be files themselves, not directories.
-d
checks if directory exists.-r -w -x
checks if file has reading, writing and executing permissions
#!/bin/bash
file=$1
#check if file exists
echo "Does file $file exist?"
test -e $file
echo $?
#check if file is a directory
echo "Does file $file is a directory?"
test -d $file
echo $?
Last updated