shell if statements code example

Example 1: bash if statement

and - &&
or - ||

# and example
if [ -r $1 ] && [ -s $1 ]
then
echo This file is useful.
fi

# or example
if [ $USER == 'bob' ] || [ $USER == 'andy' ]
then
ls -alh
else
ls
fi

Example 2: bash else if

if [ "$animal" == "penguin" ]; then
  echo "Hmmmmmm fish... Tux happy!"
elif [ "$animal" == "dolphin" ]; then
  echo "Pweetpeettreetppeterdepweet!"
else
  echo "*prrrrrrrt*"
fi

if TEST-COMMANDS; then
  CONSEQUENT-COMMANDS;
elif MORE-TEST-COMMANDS; then
  MORE-CONSEQUENT-COMMANDS;
else
  ALTERNATE-CONSEQUENT-COMMANDS;
fi

Example 3: ash if statment

if [ "$USER" == "Adam" ]
then
	echo "User is Adam"
else
	echo "User is not Adam"
fi

Tags:

Misc Example