Operators

Arithmetic

Bash does not know how to add, reduce, multiply... 2 solutions:

  1. Create variables:

    1. var=$((number operation number)); echo $var

      1. test=$((50*50)); echo $test

  2. Command 'bc':

    1. apt install bc

    2. echo "number operation number" | bc

      1. echo "50*50" | bc

Comparison

Equal
Greater
Lower

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 -> false

    • var1="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