2017-02-03 142 views
2

我试图将参数传递给我编写的脚本,但无法正确理解。Bash脚本参数

我要的是一个没有标志一个强制的说法,并与国旗两个可选参数,因此它可以被称为是这样的:

./myscript mandatory_arg -b opt_arg -a opt_arg 

./myscript mandatory_arg -a opt_arg 
./myscript mandatory_arg -b opt_arg 

我看着getopts的和得到这个:

while getopts b:a: option 
do 
    case "${option}" 
    in 
     b) MERGE_BRANCH=${OPTARG};; 
     a) ACTION=${OPTARG};; 
    esac 
done 

if "$1" = ""; then 
    exit 
fi 

echo "$1" 
echo "$MERGE_BRANCH" 
echo "$ACTION" 

但它根本不起作用。

回答

3

假设你强制性参数出现最后,那么你应该尝试下面的代码:[评论在线]

OPTIND=1 
while getopts "b:a:" option 
do 
    case "${option}" 
    in 
     b) MERGE_BRANCH=${OPTARG};; 
     a) ACTION=${OPTARG};; 
    esac 
done 

# reset positional arguments to include only those that have not 
# been parsed by getopts 

shift $((OPTIND-1)) 
[ "$1" = "--" ] && shift 

# test: there is at least one more argument left 

((1 <= ${#})) || { echo "missing mandatory argument" 2>&1 ; exit 1; }; 

echo "$1" 
echo "$MERGE_BRANCH" 
echo "$ACTION" 

结果:

~$ ./test.sh -b B -a A test 
test 
B 
A 
~$ ./tes.sh -b B -a A 
missing mandatory argument 

如果你真的想要mandato RY参数出现第一,那么你可以做以下的事情:

MANDATORY="${1}" 
[[ "${MANDATORY}" =~ -.* ]] && { echo "missing or invalid mandatory argument" 2>&1; exit 1; }; 

shift # or, instead of using `shift`, you can set OPTIND=2 in the next line 
OPTIND=1 
while getopts "b:a:" option 
do 
    case "${option}" 
    in 
     b) MERGE_BRANCH=${OPTARG};; 
     a) ACTION=${OPTARG};; 
    esac 
done 

# reset positional arguments to include only those that have not 
# been parsed by getopts 

shift $((OPTIND-1)) 
[ "$1" = "--" ] && shift 

echo "$MANDATORY" 
echo "$MERGE_BRANCH" 
echo "$ACTION" 

结果如下:

~$ ./test.sh test -b B -a A 
test 
B 
A 
~$ ./tes.sh -b B -a A 
missing or invalid mandatory argument 
+0

当试图运行这个它打印出的强制性参数,然后“ “对于可选项,如果我没有强制性地运行,它会回答”缺少强制性参数“ –

+0

不推荐先强制性参数的原因是什么?并且我认为上次编辑时丢失了一些东西 –

+0

@ A.Jac这只是*约定*和*个人品味的问题* –