Bash Scripting

Bash case statement example

#!/bin/bash
echo -n "what colour ?  red green or blue  "
read colour

case $colour in
[Bb]lu?)
  echo creating a bash subshell with blue foreground
  env PS1="\e[1;34m[\u@\h \W]\$ \e[m " bash -i
  ;;
[Gg]reen)
   echo creating a bash subshell with green foreground
   env PS1="\e[1;32m[\u@\h \W]\$ \e[m " bash -i
  ;;
red)
  echo creating a bash subshell with red foreground
  env PS1="\e[1;31m[\u@\h \W]\$ \e[m " bash -i
  ;;
*)
  echo "invalid selection" &
  ;;
esac

Bash nested if else statement

#!/bin/bash
#bash nested if else statement
if [ -z  "$1" ]
  then
    echo "Usage $0 {integer between 1-10}"
    exit 1
else
  true
fi
if [ "$1" -gt 1 ]
 then
   if [ "$1" -lt 4 ]
    then
     echo is between 2 or 3
   else
     echo is greater than or equal to 4
   fi
 else
   echo is less than  or equal to 1
fi

Bash wait for user interaction

#!/bin/bash
#echo are you sure ?
#read  VALUE

until  [[ "$VALUE" = "yes" ]]

   do
    echo "are you sure ?"
read  VALUE
done

Bash select menu example 1

#!/bin/bash
OPTIONS="Hello Quit extra"
select opt in $OPTIONS; do
        if [ "$opt" = "Quit" ]; then
          echo done
          exit
        elif [ "$opt" = "Hello" ]; then
          echo Hello World
        elif [ "$opt" = "extra" ]; then
          echo "Sorry! extra is not implemented yet"
        else
          clear
          echo bad option
        fi
done

Bash select menu example 2

#!/bin/bash
PS3="Select program: "
select program in  ls pwd date top exit
do
 $program
done

Bash shifting through arguments

#!/bin/bash
if [ "$#" == "0" ]; then
        echo "Usage: $0 ARG1 ARG2 ARG3 etc...."
        exit 1
fi

while (( "$#" ))
do
  echo -e "processing argument $1 \n"
  sleep 1
  shift
done

exit

Bash compare 2 strings #really bad dont use on production code

#!/bin/bash
#bash test compare 2 strings
#Usage: string-compare.sh string1 string2
S1=$1
S2=$2
if [ "$S1" != "$S2" ] ;then
     echo "S1('$S1') is not equal to S2('$S2')"
fi
if [ "$S1" = "$S2" ] ;then
     echo "S1('$S1') is equal to S2('$S2')"
fi

if [[ "$S1" == *"$S2"* ]]; then
   echo "String 1 contains String 2"
fi

if [[ "$S2" == *"$S1"* ]]; then
#if         [[ "*"$S1"*" == "$S2" ]]; then
   echo "String 2 contains String 1"
fi

Bash script using lock file to control another script

#!/bin/bash
answer=unset
if [ -f /tmp/stop ]
  then
   echo -e "/tmp/stop exists \n exiting"
   exit 1
else
  while [ ! -f /tmp/stop ]
    do
        echo "go" && sleep 1
  done
fi
echo stopping

Until loop example

#!/bin/bash
a=0
while [ $a -ne 10 ]
do 
    echo $a
    a=$(( $a +1 ))
done

While loop example

#!/bin/bash
a=0
until [ $a -gt 10 ]
do 
    echo $a
    a=$(( $a +1 ))
done