Search code examples
bashunixshellgetoptgetopts

how to use getopt(s) as technique for passing in argument in bash


Can someone show me an example how to use getopts properly or any other technique that I would be able to pass in an argument? I am trying to write this in unix shell/bash. I am seeing there is getopt and getopts and not sure which is better to use. Eventually, I will build this out to add for more options.

In this case, I want to pass the filepath as input to the shell script and place a description in the case it wasn't entered correctly.

export TARGET_DIR="$filepath"

For example: (calling on the command line)

./mytest.sh -d /home/dev/inputfiles

Error msg or prompt for correct usage if running it this way:

./mytest.sh -d /home/dev/inputfiles/

Solution

  • As a user, I would be very annoyed with a program that gave me an error for providing a directory name with a trailing slash. You can just remove it if necessary.

    A shell example with pretty complete error checking:

    #!/bin/sh
    
    usage () {
      echo "usage: $0 -d dir_name"
      echo any other helpful text
    }
    
    dirname=""
    while getopts ":hd:" option; do
      case "$option" in
        d)  dirname="$OPTARG" ;;
        h)  # it's always useful to provide some help 
            usage
            exit 0 
            ;;
        :)  echo "Error: -$OPTARG requires an argument" 
            usage
            exit 1
            ;;
        ?)  echo "Error: unknown option -$OPTARG" 
            usage
            exit 1
            ;;
      esac
    done    
    
    if [ -z "$dirname" ]; then
      echo "Error: you must specify a directory name using -d"
      usage
      exit 1
    fi
    
    if [ ! -d "$dirname" ]; then
      echo "Error: the dir_name argument must be a directory
      exit 1
    fi
    
    # strip any trailing slash from the dir_name value
    dirname="${dirname%/}"
    

    For getopts documentation, look in the bash manual