Programing - Paiet/Tech-Journal-for-Everything GitHub Wiki
If/Then Statements
Script with user input
#! /bin/bash
read -p "Enter Firstname: " FNAME
read -p "Enter Lastname: " LNAME
echo "Full Name: $FNAME $LNAME"
Script modified to include arguments
#! /bin/bash
FNAME=$1
LNAME=$2
if [ "$FNAME" = "" ]; then
read -p "Enter Firstname: " FNAME
read -p "Enter Lastname: " LNAME
fi
echo "Full Name: $FNAME $LNAME"
If/Then/Else
#! /bin/bash
FNAME=$1
LNAME=$2
if [ "$FNAME" = "" ]; then
read -p "Enter Firstname: " FNAME
read -p "Enter Lastname: " LNAME
else
echo "Inline variables detected"
fi
echo "Full Name: $FNAME $LNAME"
- Test
- Performs testing logic
- Logic is placed between
[
and]
- Logic is placed between
- Tons of options
-a
and-e
Does a file exist-d
Does a directory exist-w
Is the file writable-x
Is the file executable
- Comparisons
-a
And-o
Or-nt
Newer than-ot
Older than-eq
and=
Equal-ne
and!=
Not equal-gt
/-ge
Greater than (or equal)-lt
/-le
Less than (or equal)
- Performs testing logic
Shorthand Notation
dirname="/tmp/testdir"
[ -e $dirname ] && echo $dirname already exists || mkdir $dirname
&&
represents "then"||
represents "else"
Case
- Combines multiple if statements
case `date +%a` in
"Sat")
tar -czf ~/Backups/weekly.tgz ~/Documents
;;
"Mon" | "Wed" | "Fri")
tar -czf ~/Backups/daily.tgz ~/Documents
;;
# No Backups any other day
*)
;;
esac
For/Do Loops
- Performs an action repeatedly
for NAME in John Paul Ringo George ; do
echo $NAME is my favorite Beatle
done
for FILE in `/bin/ls`
do
echo $FILE
done
for FILE in ~/Backups/*
do
tar -czf $FILE.tgz $FILE
done
While/Do and Until/Do
- While/Do executes while a statement is true
- Until/Do executes while a statement is false
N=0
while [ $N -lt 10 ] ; do
echo -n $N
let N=$N+1
done
N=0
until [ $N -eq 10 ] ; do
echo -n $N
let N=$N+1
done