如何创建一个bash脚本接受参数

如何创建一个bash脚本接受参数

本文介绍了如何创建一个bash脚本接受参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经知道getopts的,这是好的,但很烦人,你必须有一个标志,甚至是强制性的参数。

I already know about getopts, and this is fine, but it is annoying that you have to have a flag even for mandatory arguments.

在理想情况下,我希望能够有接收这种形式参数的脚本:

Ideally, I'd like to be able to have a script which receives arguments in this form:

script.sh [optional arguments] [anything required]

例如:

script.sh -rvx output_file.txt

该脚本说,你必须有一个输出文件。有没有简单的方法来做到这一点?

where the script says you HAVE to have an output file. Is there any easy way to do this?

据我所知,有getopts的那就要看起来像: script.sh -rvx -f output_file.txt ,那就是不是很干净。

As far as I know, with getopts it would have to look like: script.sh -rvx -f output_file.txt, and that is just not very clean.

我也可以根据需要使用Python,但只有2.4可用,这是一个有点过时了。

I can also use python if necessary, but only have 2.4 available, which is a bit dated.

推荐答案

不要使用getopts的内置,使用的getopt(1)代替。他们是(巧妙地)不同,做不同的事情做好。对于你的情况,你可以这样做:

Don't use the getopts builtin, use getopt(1) instead. They are (subtly) different and do different things well. For you scenario you could do this:

#!/bin/bash

eval set -- $(getopt -n $0 -o "-rvxl:" -- "$@")

declare r v x l
declare -a files
while [ $# -gt 0 ] ; do
        case "$1" in
                -r) r=1 ; shift ;;
                -v) v=1 ; shift ;;
                -x) x=1 ; shift ;;
                -l) shift ; l="$1" ; shift ;;
                --) shift ;;
                -*) echo "bad option '$1'" ; exit 1 ;;
                *) files=("${files[@]}" "$1") ; shift ;;
         esac
done

if [ ${#files} -eq 0 ] ; then
        echo output file required
        exit 1
fi

[ ! -z "$r" ] && echo "r on"
[ ! -z "$v" ] && echo "v on"
[ ! -z "$x" ] && echo "x on"

[ ! -z "$l" ] && echo "l == $l"

echo "output file(s): ${files[@]}"

编辑:完整性我提供的处理需要一个参数的选项为例

for completeness I have provided an example of handling an option requiring an argument.

这篇关于如何创建一个bash脚本接受参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 16:48