Shell Scripting - Part 4

From CDOT Wiki
Jump to: navigation, search

Purpose of Shell Scripting - Part 4

Online Scripting Resources

If you require additional practice in creating shell scripts and using the vi text editor, run the commands in your Matrix account:


Scripting Content

Bash Shell Scripting Tips


  • The case statement:

    The case statement is a control-flow statement that works in a similar way as the if-elif-else statement (but is more concise). This statement presents scenerios or "cases" based on values or regular expressions (not ranges of values like if-elif-else statements). After action(s) are taken for a particular scenerio (or "case"), a break statement (;;) is used to "break-out" of the statement (and not perform other actions). A default case (*) is also used to catch exceptions.

    Examples (try in shell script):

    read -p "pick a door (1 or 2): " pick
    case $pick in
      1) echo "You win a car!" ;;
      2) echo "You win a bag of dirt!" ;;
      *) echo "Not a valid entry"
         exit 1 ;;
    esac


    read -p "enter a single digit: " digit
    case $digit in
      [0-9]) echo "Your single digit is: $digit" ;;
             *) echo "not a valid single digit"
                 exit 1 ;;
    esac


  • The getopts function:

The getopts function allows the shell scripter to create scripts that accept options (like options for Linux commands). This provides the Linux administrator with scripts that provide more flexibility and versatility. A built-in function called getopts (i.e. get command options) is used in conjunction with a while loop and a case statement to carry out actions based on if certain options are present when the shell script is run. The variable $OPTARG can be used if an option accepts text (denoted in the getopts function with an option letter followed by a colon. Case statement exceptions use the :) and \?) cases for error handling.

Example of getopts (try in script and run with options)

while getopts abc: name
do
  case $name in
    a) echo "Action for option \"a\"" ;;
    b) echo "Action for option \"b\"" ;;
    c) echo "Action for option \"c\""
        echo Value is: $OPTARG" ;;
    :) echo "Error: You need text after -c option"
        exit 1 ;;
    \?) echo "Error: Incorrect option"
        exit 1 ;;
esac