72 lines
1.9 KiB
Bash
72 lines
1.9 KiB
Bash
#!/bin/bash -e
|
|
|
|
#####################################################
|
|
#
|
|
# If/else statements allow you to run select commands
|
|
# if conditions are met or if they are not.
|
|
#
|
|
# Usage: bash bash/ifelse.sh
|
|
#
|
|
#####################################################
|
|
|
|
NUMBER=3
|
|
COMPARE="Compare this string"
|
|
SUBSTRING="not"
|
|
SUBSTRING2="this"
|
|
|
|
# Evaluate whether two numbers are equal with the "-eq" operator
|
|
if [ ${NUMBER} -eq 3 ]; then
|
|
echo "Variable \$NUMBER is equal to 3"
|
|
else
|
|
echo "Variable \$NUMBER is NOT equal to 3"
|
|
fi
|
|
|
|
sleep 2
|
|
|
|
# Evaluate whether a string contains substrings. Uses the
|
|
# "elif" operator to check if a second condition is met if
|
|
# the first one fails.
|
|
if [[ "${COMPARE}" == *"${SUBSTRING}"* ]]; then
|
|
echo "String \$COMPARE contains substring \"${SUBSTRING}\""
|
|
elif [[ "${COMPARE}" == *"${SUBSTRING2}"* ]]; then
|
|
echo "String \$COMPARE contains substring \"${SUBSTRING2}\""
|
|
else
|
|
echo "String \$COMPARE contains none of the substrings"
|
|
fi
|
|
|
|
sleep 2
|
|
|
|
# Evaluate whether a file exists with the "-f" operator
|
|
if [ -f "text/cat1.txt" ]; then
|
|
echo "File text/cat1.txt exists. Here are the contents:"
|
|
cat text/cat1.txt
|
|
else
|
|
echo "File text/cat1.txt does NOT exist"
|
|
fi
|
|
|
|
sleep 2
|
|
|
|
# Evaluate whether a directory exists with the "-d" operator
|
|
if [ -d "not_here" ]; then
|
|
echo "Directory not_here exists. Here are the contents:"
|
|
ls not_here
|
|
else
|
|
echo "Directory not_here does NOT exist"
|
|
fi
|
|
|
|
# Evaluate whether or not one condition OR another
|
|
# is met using the "||" operators.
|
|
# The "-gt" operator determines if a number is
|
|
# greater than a compared number and "-lt" for
|
|
# less than.
|
|
if [ $NUMBER -gt 1 ] || [ $NUMBER -lt 5]; then
|
|
echo "Variable \$NUMBER is greater than 1 or less than 5"
|
|
fi
|
|
|
|
# Evaluate whether both conditions are met using
|
|
# the AND operator "&&"
|
|
if [[ "${COMPARE}" == *"${SUBSTRING}"* ]] && [[ "${COMPARE}" == *"${SUBSTRING2}"* ]]; then
|
|
echo "String \$COMPARE contains both substrings"
|
|
else
|
|
echo "String \$COMPARE does not contain both substrings"
|
|
fi |