在getopts之后解析参数

时间:2012-02-27 21:51:13

标签: bash command-line-arguments arguments getopts

我想像这样调用一个bash脚本

$ ./scriptName -o -p -t something path/to/file

这是我得到的

#!/bin/bash

o=false
p=false

while getopts ":opt:" options
do
    case $options in
        o ) opt1=true
        ;;
        p ) opt2=true
        ;;
        t ) opt3=$OPTARG
        ;;
    esac
done

但如何获得path/to/file

2 个答案:

答案 0 :(得分:38)

您可以执行以下操作:

shift $(($OPTIND - 1))
first_arg=$1
second_arg=$2
循环运行后

答案 1 :(得分:5)

要在getopts处理之后捕获所有剩余参数,一个好的解决方案是shift(删除)所有已处理参数(变量$OPTIND)并分配剩余参数({ {1}})到特定变量。 简短答案:

$@

大量示例:

shift $(($OPTIND - 1))
remaining_args="$@"

这将输出

#!/bin/bash

verbose=false

function usage () {
    cat <<EOUSAGE
$(basename $0) hvr:e:
    show usage
EOUSAGE
}

while getopts :hvr:e: opt
do
    case $opt in
        v)
            verbose=true
            ;;
        e)
            option_e="$OPTARG"
            ;;
        r)
            option_r="$option_r $OPTARG"
            ;;
        h)
            usage
            exit 1
            ;;
        *)
            echo "Invalid option: -$OPTARG" >&2
            usage
            exit 2
            ;;
    esac
done


echo "Verbose is $verbose"
echo "option_e is \"$option_e\""
echo "option_r is \"$option_r\""
echo "\$@ pre shift is \"$@\""
shift $((OPTIND - 1))
echo "\$@ post shift is \"$@\""