IT 3110 : Advanced System Administration

Shell Logic

Arithmetic

Use $(( )) for integer arithmetic

    z=$((24+12*2))
    z=$((z**2))
    b=$((z+=1))
  • Note that you don't need $ in front of var if in parens

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

  • What's the difference between square and round brackets?
    • Round brackets are strictly for numeric expressions.
    • Square brackets can be used for file characteristics

Testing for file characteristics

  • Make sure file exists

      if [ -e "foo.txt" ]
    
  • See table 6-2 to see other unary file characteristic operators.

  • All the file test conditions include an implicit test for existence, so you don’t need to test if a file exists and is readable. It won’t be readable if it doesn’t exist.

Test values of strings

Maybe you got from user input?

    if [ -n "$VAR" ]

The -n checks to see if var is not null.
Use a -z to see if a string is null.
Should always double quote the string when testing.

Bash comparison operators

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

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

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