UNIX‎ > ‎

Shell scripting: program controls part 1

Welcome to art of scripting!!
Here I am posting a list of experiments on bash shell if condition command.
  1. if-fi condition
  2. if-else-fi condition
  3. if-elif-else-fi ladder
Lets test with numeric variable values and also test file exist or else using the true or false command in the if condition.
#!/bin/bash
##############################################################################
#
# FileName              :       simpleif.sh
#
# Author                :       Pavan
#
# Updated date          :       28/01/2016
#
# Description           :       This script will be use to illustrate the if-fi
#
##############################################################################

if cat simpleif.sh; then  echo 'File display true because it exists'; fi

# if will excute a command when no braces used

if [ -f simpleif.sh ]; then
        echo "simpleif.sh file exists..."
fi

# boolean values are defined true, false remember case sensitive
if true; then
        echo "True command"
fi

if ! false; then
        echo "Not false that is true!!"
fi


Execution of the above script will gives output as follows:
if condition in bash shell scripting

if-else-if condition in shell scripting

#!/bin/bash

read -p "Please enter two numbers: " a b

echo "Given numbers: $a $b"

if [[ $a > $b ]]; then
  echo "a is greater than b"
else
  echo "b is greater than a"
fi

Execution of the above script...


if-elif-else-if Ladder - Menu program in Shell script


#!/bin/bash

echo "Choose your option"
echo -e "\t1. Memory usage \n \
        2. Disk usage \n \
        3. CPU Utilization \n \
        0. Quit \n"
read ch
if [[ ch -eq 1 ]]; then
 echo -e 'The Memory usage...\n'; free -m
elif [[ ch -eq 2 ]]; then
 echo -e 'The Disk utilization lll\n'; df -h .
elif [[ ch -eq 3 ]]; then
 echo -e 'The CPU utlization ...\n'; uptime
else
        exit
fi

Execution of the menu program will be as shown:


Logical operators in Shell script

#!/bin/bash
# Description   : This script will illustrates the logical operator in shell script
#

c=1

if [[ 10 < 30 && $c < 5 ]]; then
        echo "a is true"
fi


if (( $c && 1 )); then
 echo -e "all true..."
else
 echo "something wrong"
fi

if [[ $c -lt 10 ]] || [[ 100 -gt $c ]]; then
        echo "Either one of them is true..."
else
        echo "Both are false"
fi
Execution of logical.sh script as follows: