IT 3110 : Advanced System Administration

Shell Logic


Arithmetic

Use $(( )) for integer arithmetic

    z=$((24+12*2))
    z=$((z**2))
    b=$((z+=1))

Decisions with if

if [ $# -lt 3 ]
then
    printf "%b" "Error. Not enough arguments.\n"
    printf "%b" "usage: myscript file1 op file2\n"
    exit 1
fi

Decisions

    if (( b == 12 )); then echo 'foo'; else echo 'bar'; fi

Could put on separate lines and omit the semicolons


Decisions


Testing for file characteristics


Test values of strings

Maybe you got from user input?

    if [ -n "$VAR" ]

The -n checks to see if var has text.


Bash comparison operators

These only apply if you are using the [ ] notation.

Numeric String
-lt <
-le <=
-gt >
-ge >=
-eq =, ==
-ne !=

We probably should use the ( ) notation if comparing numbers.


Comparison samples

(( 3 == 3 )) && echo "yes"
(( 3 == 3 )) && echo "yes" || echo "no"
(( 3 == 4 )) && echo "yes" || echo "no"
[[ 3 == 4 ]] && echo "yes" || echo "no"
[[ '3' == '4' ]] && echo "yes" || echo "no"
[[ '3' -eq '4' ]] && echo "yes" || echo "no"
[[ '3' -eq '3' ]] && echo "yes" || echo "no"
[[ '3' = '3' ]] && echo "yes" || echo "no"
[[ '3' == '3' ]] && echo "yes" || echo "no"

While loops

    i=0
    while (( i < 5 )); do echo $i; ((i++)); done

    while read foo; do echo "i am $foo"; done

For the above read loop, you could also call it like:

    ./bar.sh < cows.txt #assuming the script was named bar.sh

While loop reading from a file

    while read foo; do echo "i am $foo"; done < cows.txt

or

    while read foo 
    do 
      echo "$foo is a single line from that file"
    done < cows.txt

For loops

    for (( i=0 ; i < 10 ; i++ )) ; do echo $i ; done
for i in $(seq 1 10); do echo $i; done
for i in {1..10}; do echo $i; done
for name in tom fred stan; do echo $name; done