Ubuntu – Shell script options with parsing arguments

bashcommand linescripts

I have the shell script

CONTROLLER_IP=""
if [ "$#" -eq 1 ]
then
    CONTROLLER_IP=$1
else
    echo "Usage : create_endpoint.sh --controller-ip <Controller IP>"
    exit 1
fi

but its executing like this ./create_endpoint.sh 10.10.10.1

I want to execute like this /create_endpoint.sh --controller-ip 10.10.10.1

Best Answer

  • Something like this:

    #!/bin/bash
    CONTROLLER_IP=""
    
    while [ "$1" != "" ]; do
      case $1 in
        -c|--controller-ip)
          if [ -n "$2" ]; then
            CONTROLLER_IP="$2"
            shift 2
            continue
          else
            echo "ERROR: '--controller-ip' requires a non-empty option argument."
            exit 1
          fi
            ;;
        -h|-\?|--help)
          echo "Usage: $(basename $0) --controller-ip <ip>"
          exit
          ;;
        --)              # End of all options.
          shift
          break
          ;;
        -?*)
          echo "WARN: Unknown option (ignored): $1"
          ;;
        *)               # Default case: If no more options then break out of the loop.
          break
      esac
      shift
    done
    
    echo "$CONTROLLER_IP"
    

    Examples

    $ ./foo --controller-ip 192.168.2.1
    192.168.2.1
    
    $ ./foo -c 192.168.2.1
    192.168.2.1
    
    $ ./foo --controller-ip
    ERROR: '--controller-ip' requires a non-empty option argument.
    
    $ ./foo --help
    Usage: foo --controller-ip <ip>
    
    $ ./foo -help
    WARN: Unknown option (ignored): -help
    

    As OP commented:

    I don't want help option.

    #!/bin/bash
    CONTROLLER_IP=""
    
    while [ "$1" != "" ]; do
      case $1 in
        -c|--controller-ip)
          if [ -n "$2" ]; then
            CONTROLLER_IP=$2
            shift 2
            continue
          else
            echo "ERROR: '--controller-ip' requires a non-empty option argument."
            exit 1
          fi
            ;;
        --)              # End of all options.
          shift
          break
          ;;
        -?*)
          echo "WARN: Unknown option (ignored): $1"
          ;;
        *)               # Default case: If no more options then break out of the loop.
          break
      esac
        shift
    done
    
    echo "$CONTROLLER_IP"