分析输入的更好的办法 [英] Better way of parsing the input

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

问题描述

我的shell脚本发生在一组输入变量的一些是可选的。输入应遵循以下签名。

My shell script takes in a set of input variables some are optional. The input should follow the following signature.

myscript.sh VAR1 VAR2 [-x VAR3] [-y VAR4]`。

myscript.sh var1 var2 [-x var3] [-y var4]`.

-x和-y是的可选输入这些选项可以在任何位置出现(VAR1&安培之间; VAR 2或在启动),但VAR3总会preceed VAR4。此外VAR1将preceed变种2

The -x and -y are optional inputs and these options can occur at any location (between var1 & var 2 or at the start) but var3 will always preceed var4. Also var1 will preceed var 2.

脚本我有做了很多的if else检查,以覆盖所有的可能性。
事情是这样的。

The script I have does a lot of if else checks to cover all the probabilities. Something like this

if [ $1 == "-x" ]; then
## Then check if $3 == "-y" 
## Assign values to VAR1 , VAR2, VAR3, VAR4 
## else check for other possibilities
fi

我想知道是否有这样做的,分配给变量的一个更好的办法?

I was wondering if there was a better way of doing this and assigning the values to variables?

推荐答案

与测试,以确保选配参数,如果提供,只提供一次。

with a test to ensure that optionals arguments, if provided, are provided only once.

#!/bin/bash

die() {
    echo >&2 $@
    exit 1
}

declare -a vars_1_2
var1='' var2='' var3='' var4=''
while [ "$1" ];do
    case $1 in
        -x ) [ "$var3" ] && die "Argument '-x' provided twice!"
             shift
             var3=$1
             shift
             ;;
        -y ) [ "$var4" ] && die "Argument '-y' provided twice!" 
             shift
             var4=$1
             shift
             ;;
        * ) vars_1_2+=($1) ; shift ;;
    esac
done
[ ${#vars_1_2[@]} -ne 2 ] && \
    die "Needed exactly 2 positional arguments. Got ${#vars_1_2[@]}."
var1=${vars_1_2[0]}
var2=${vars_1_2[1]}
set | grep ^var

$ ./parsargs.sh 12 33 -x 45 -y 67 -x 2
Argument '-x' provided twice!

$ ./parsargs.sh 12 -x 45 -y 67 
Needed exactly 2 positional arguments. Got 1.

$ ./parsargs.sh 12 34 -x 45 -y 67 
var1=12
var2=34
var3=45
var4=67
vars_1_2=([0]="12" [1]="34")

这篇关于分析输入的更好的办法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆