#!/bin/bash

# The if construction allows you to build conditional statements
# Syntax:
#         if TEST-COMMANDS; then CONSEQUENT-COMMANDS; fi
# or:
#         if TEST-COMMANDS
#         then
#             CONSEQUENTE-COMMANDS
#         fi
# 
# (Try to understand why you have to put ';' if you use one liner.)
#
# The TEST-COMMANDS is executed and if its return status is zero, the
# CONSEQUENT-COMMANDS are executed.
# The TEST-COMMANDS could be any command that return a zero/non-zero
# status, but a comparison is often used.
#
# Primary expressions (some):
#   [ -flag FILE]: flag indicates property of file.
#                  -a=exists, -r=readable, -w=writable, etc.
#                  Lots of options!
#   [ FILE1 -op FILE2]: -nt=FILE1 has been changed more recently than FILE2
#                       -ot=FILE1 is older than FILE2
#                       etc.
#   [ S1 op S2]: string comparison (=, !=, <=, >=)
#   [ A1 op A2]: arithmetic binary operators (-eq, -ne, -lt, -le, -gt, -ge)
#
# Combining expressions:
#     ! [ EXPR ]
#     [ EXPR ] && [ EXPR ]
#     [ EXPR ] || [ EXPR ]
#
# Note: '[' is a program (run 'which [' to locate it).
# That's why it must be surrounded by spaces.
# (Sometimes is an alias to the 'test' program, that we will discuss soon.) 
#
# Examples:

foo="test"
if [ "$foo" = "test" ]
then
     echo "foo is test"
fi

bar=2
if [ "$bar" -lt 10 ]; then echo "bar is less than 10"; fi

myfilename="foobar.txt"
touch "$myfilename"
if [ -a "$myfilename"  ]
then
     echo "File $myfilename exists" 
fi
rm "$myfilename"


# You can also use elif and else
bar=5
if [ "$bar" -gt 10 ];
then
    echo "bar is greater than 10"
elif [ "$bar" -gt 3 ]
    echo "bar is greater than 3"
else
    echo "bar is 3 or less"
fi

# Combining expresions
x=0
y=3
if [ "$x" -ne 0 ] && [ "$y" -lt 10 ]
then
     echo "x is not 0 and y is less than 10"
fi

x=0
y=1
if ! [ "$x" -eq 0 ] && ! [ "$y" -eq 0 ]; then
     echo "both x and y are not zero"
else
     echo "either x or y (or both) are zero""
fi



