Search code examples
stringbashdockergetopts

How can I check if the value of argument provided from GETOPTS is equal to specific string?


Im writing bash script which will build a docker image locally or remotely depending on the argument provided.

Im struggling with checking if the provided string is equal to "remote" or "local".

When I execute script, it doesn't accept any number, but it does accept any string.

!/bin/bash

usage() { echo "Usage: $0 [-m < local|remote>]" 1>&2; exit 1; }

while getopts "m:" o; do
    case "${o}" in
        m)
            destination=${OPTARG}
            ((destination == "local" || destination == "remote")) || usage
            ;;
        *)
            usage
            ;;
    esac
done
shift "$((OPTIND-1))"

echo $destination

Solution

  • So really the only change you need to make is to change your ((...)) statement to a [[ ... ]] statement as @Nahuel Fouilleul suggested and add $'s to your destination variables. Their suggestion didn't work for you however because destination was spelled wrong. I have the updated code shown below.

    #!/bin/bash
    
    usage() { echo "Usage: $0 [-m < local|remote>]" 1>&2; exit 1; }
    
    while getopts "m:" o; do
      case "${o}" in
        m)
            destination=${OPTARG}
            [[ $destination == "local" || $destination == "remote" ]] || usage
            ;;
        *)
            usage
            ;;
      esac
    done
    
    shift "$(( OPTIND-1 ))"
    
    echo $destination
    

    However, you don't need to check for this information in the switch statement, you could do a check in the main part of your code and ensure that destination has been set using parameter expansion as I show here:

    ...
        m)
            destination=${OPTARG}
            ;;
    ...
    
    [[ ${destination:?A destination is required.} == "local" || ${destination} == "remote" ]] || usage
    
    echo $destination