Advertisement
justin_hanekom

Bash parse command-line function

Mar 2nd, 2019
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 2.11 KB | None | 0 0
  1. ################################################################################
  2. # Function:     parse_cmdline
  3. # Description:  Parses the command-line using the enhanced version of getopt
  4. # Arguments:    $@ :- Command-line arguments (required)
  5. # Requires:     Global variables $USER_NAME, $DEST_DIR, $IS_REMOVE, and
  6. #               $IS_VERBOSE
  7. # Outputs:      Sets above-mentioned global variables based on given
  8. #               command-line arguments
  9. function parse_cmd_line {
  10.     # Ensure that the enhanced version of getopt is available
  11.  
  12.     ! getopt --test > /dev/null
  13.     if (( "${PIPESTATUS[0]}" != 4 )); then
  14.         echo "I'm sorry, the enhanced version of getopt is required. Exiting." >&2
  15.         exit 1
  16.     fi
  17.  
  18.     # Initialize the global variables
  19.  
  20.     USER_NAME=''
  21.     DEST_DIR=''
  22.     IS_VERBOSE=''
  23.     IS_REMOVE=''
  24.  
  25.     # Parse the command-line options
  26.  
  27.     if ! readonly PARSED_OPTIONS=$(getopt --options=${OPTIONS} \
  28.                                     --longoptions=${LONGOPTS} \
  29.                                     --name "$(basename "$0")" -- "$@"); then
  30.         echo 'Unknown error parsing getopt options. Exiting.' >&2
  31.         exit 2
  32.     fi
  33.  
  34.     eval set -- "${PARSED_OPTIONS}"
  35.  
  36.     # Extract and validate command-line options and their arguments, if any
  37.  
  38.     while (( $# >= 1 )); do
  39.         case "$1" in
  40.             -u|--user)
  41.                 USER_NAME=$(trim "$2") ; shift 2
  42.                 ;;
  43.             -d|--destdir)
  44.                 DEST_DIR=$(chomp_slash "$(trim "$2")") ; shift 2
  45.                 ;;
  46.             -r|--remove)
  47.                 IS_REMOVE='true' ; shift
  48.                 ;;
  49.             -v|--verbose)
  50.                 IS_VERBOSE='true' ; shift
  51.                 ;;
  52.             -h|--help)
  53.                 usage_exit 0
  54.                 ;;
  55.             --)
  56.                 shift ; break
  57.                 ;;
  58.             *)
  59.                 usage_exit 3 >&2
  60.                 ;;
  61.         esac
  62.     done
  63.  
  64.     # Ensure that required options have been supplied
  65.  
  66.     if [[ -z "${USER_NAME}" || -z "${DEST_DIR}" ]]; then
  67.         usage_exit 4 >&2
  68.     fi
  69. } # parse_cmd_line
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement