Difficulty in parsing the input arguments

2019-08-25 04:32发布

The input to my shell should follow the following signature.

myscript.sh var1 var2 [-o var3] [-r var4].

The -o and -r are optional inputs and these options can occur at any location (between var1 & var 2 or at the start/end) but var3 will always preceed var4 if var 3 is specified. Also var1 will preceed var 2.

#!/bin/bash

case "$#" in
([01]) echo "Usage: $0 var1 var2 [-o val3] [-r val4]" >&2; exit 1;;
esac

VAR1="$1"
VAR2="$2" 
VAR3=
VAR4=


while getopts ":o:r:" opt; do
  case $opt in
    o)
     VAR3=$OPTARG
      ;;
    r)
     VAR4=$OPTARG 
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

shift $(( OPTIND - 1 ))


    if [ -z "${VAR3+xxx}" ] && [ -z "${VAR4+xxx}" ];
    then
    echo $1 $2;
    elif [ -z "${VAR3+xxx}" ]; 
    then
    echo $1 $2 $VAR4;
    elif [ -z "${VAR4+xxx}" ];
    then 
    echo $1 $2 $VAR3;
    else
    echo $1 $2 $VAR3 $VAR4;
    fi

How to handle the case where the optional arguments are inbetwen var1 & var2

标签: linux bash shell
1条回答
迷人小祖宗
2楼-- · 2019-08-25 05:01

Your calling convention is fighting the classic calling convention of 'options and arguments first'. So, you will need to do:

case "$#" in
([01]) echo "Usage: $0 var1 var2 [-o val1] [-r val2]" >&2; exit 1;;
esac

VAR1="$1"
VAR2="$2"
shift 2

# Now use your getopts loop...
查看更多
登录 后发表回答