View on GitHub

Computational Techniques for Life Sciences

CASE statement

Purpose

Compare each value of an array or loop to known values.

Syntax

case "$variable" in

   "$condition1" )
         command...
         ;;

   "$condition2" )
         command...
         ;;

esac
#! /bin/bash

while [ $# -gt 0 ]; do    # Until you run out of parameters . . .
  case "$1" in
    -d|--debug)
              # "-d" or "--debug" parameter?
              DEBUG=1
              ;;
    -c|--conf)
              CONFFILE="$2"
              shift
              if [ ! -f $CONFFILE ]; then
                echo "Error: Supplied file doesn't exist!"
                exit $E_CONFFILE     # File not found error.
              fi
              ;;
  esac
  shift       # Check next set of parameters.
done

EXERCISE:

Create a bash script that lists all the files in your directly and matches their extensions to known types.

prompt> vi filetype.sh
#!/bin/bash
for filename in $(ls)
do
	# Take extension available in a filename
        ext=${filename##*\.}
        case "$ext" in
        c) echo "$filename : C source file"
           ;;
        o) echo "$filename : Object file"
           ;;
        sh) echo "$filename : Shell script"
            ;;
        txt) echo "$filename : Text file"
             ;;
        *) echo " $filename : Not processed"
           ;;
esac
done
prompt> chmod +x filetype.sh
prompt> ./filetype.sh
1j6z.pdb : Not processed
2a42.pdb : Not processed
actin.fa : Not processed
cnt_res.sh : Shell script
cp_orig.sh : Shell script


Prev FOR LOOPS | Next SUBFUNCTIONS | UP : BASH scripting | Top : Course Overview © 2017 Texas Advanced Computing Center