本文介绍了解析输入参数困难的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的shell的输入应遵循以下签名.

The input to my shell should follow the following signature.

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

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

-o和-r是可选输入,这些选项可以出现在任何位置(在var1和var 2之间或在开始/结束之间),但是如果指定了var 3,则var3将始终位于var4之前.var1也将在var 2之前.

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

如何处理可选参数包含在var1&中的情况var2

推荐答案

您的调用约定正在与选项和参数优先"的经典调用约定作斗争.因此,您需要执行以下操作:

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...

这篇关于解析输入参数困难的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 20:19