Shell Script case Statement

Multi-branching scripts are used when you have single variable and validated across multiple values then best option is to use case-esac.

#!/bin/bash
#
# Description   : This script takes two arguments one is option, and another File or Dir
# One of the option selected then the script will do the action accordingly.
#

option="${1}"
case ${option} in
   -f) FILE="${2}"
      echo "File name is $FILE"
      file $FILE
      ;;
   -d) DIR="${2}"
      echo "Dir name is $DIR"
      echo "listing the dir ... $DIR"
      ls -l $DIR
      ;;
   *)
      echo -e "Usage:\n ${0} [-f file] | [-d directory]"
      exit 1 # Exiting program with status 1
      ;;
esac

Execution of the script:


Comments