Skip to content

Options

Note: You can use the 'Copy to clipboard' icon to copy any code block to reset any file at any time.

Lab

This is the original contents of the lab file (../labs/05-options/05-options.lab.sh).

Follow the instructions in the file to solve the lab.

sobash_assert_parsed_options_are_valid() {

  # update the placeholder args on the next line so that
  # the case statement does NOT return 2.
  set -- "argOne" "argTwo" "argThree" "argFour" 

  if [[ "$#" == "0" ]]; then
    echo -e "\n[FAIL] ${FUNCNAME[0]} | No options passed."
    return 3
  fi

  until [[ "$#" -lt "1" ]]; do
    case "${1,,}" in
      -i|--info)
        echo -e "\n[INFO] ${FUNCNAME[0]} | User passed -i."
    shift 1
    ;;
      -w|--warn)
        echo -e "\n[WARN] ${FUNCNAME[0]} | User passed -w flag with option ($2)."
    shift 2
    ;;
      *)
    echo -e "\n[FAIL] ${FUNCNAME[0]} | User passed invalid flag ($1)." 1>&2
        return 2
    ;;
    esac
  done

}

Test

This is the original contents of the test file (../labs/05-options/05-options.test.sh).

Review the test cases and your lab file.

Will the lab file (../labs/05-options/05-options.lab.sh) pass all test cases?

#!/usr/bin/env bash

test_assert_parsed_options_are_valid() {

   ../build/sobash assert-parsed-options-are-valid
   assertEquals 0 $?

}

source ./shunit2

When ready, run the following to execute the tests above against the lab file:

cd "${HOME}/bash-programming/src/" \ 
  && ./test.sh lab 05-options

Solution

This is the original contents of the solution file (../labs/05-options/05-options.solution.sh).

This file contains an example of a viable solution that passes all the test cases.

sobash_assert_parsed_options_are_valid() {

  set -- "-i" "-w" "warnArg" "--warn" "anotherWarnArg"

  if [[ "$#" == "0" ]]; then
    echo -e "\n[FAIL] ${FUNCNAME[0]} | No options passed."
    return 3
  fi

  until [[ "$#" -lt "1" ]]; do
    case "${1,,}" in
      -i|--info)
        echo -e "\n[INFO] ${FUNCNAME[0]} | User passed -i."
    shift 1
    ;;
      -w|--warn)
        echo -e "\n[WARN] ${FUNCNAME[0]} | User passed -w flag with option ($2)."
    shift 2
    ;;
      *)
    echo -e "\n[FAIL] ${FUNCNAME[0]} | User passed invalid flag ($1)." 1>&2
        return 2
    ;;
    esac
  done

}

Run the following to execute the tests above against the solution file:

cd "${HOME}/bash-programming/src/" \ 
  && ./test.sh solution 05-options

Feel free to run the following to override the contents of the lab file with the solution file.

cd "${HOME}/bash-programming/labs/" \ 
  && cp ./05-options/05-options.{solution,lab}.sh