当第N个参数等于“--check”时如何确保N + 1参数存在

时间:2013-08-24 21:05:21

标签: bash arguments

我正在尝试编写代码来检查是否有任何参数(在位置N上)等于“--check”,如果它是真的,则要求下一个参数(位置N + 1)存在。否则,退出。

我如何实现这一目标?

我正在尝试这样但它似乎不起作用: 我重复论证,如果找到“--check”,然后将FLAG设置为1,触发nextArg的另一个条件检查:

FLAG=0   
for i in "$@"; do     

    if [ $FLAG == 1 ] ; then  
            nextARG="$i"  
            FLAG=0  
    fi  
    if [ "$i" == "--check" ] ; then  
            FLAG=1  
    fi  
done  

if [ ! -e $nextARG ] ; then  

    echo "nextARG not found"  
    exit 0
fi

2 个答案:

答案 0 :(得分:2)

我会选择getopts。该链接显示了如何检查缺失参数的示例。

答案 1 :(得分:1)

你可以使用这样的表格。我在解析参数时将它用作一般方法。我发现它比使用getopts更容易混淆。

while [[ $# -gt 0 ]]; do
    case "$1" in
    --option)
        # do something
        ;;
    --option-with-arg)
        case "$2" in)
        check_pattern)
            # valid
            my_opt_arg=$2
            ;;
        *)
            # invalid
            echo "Invalid argument to $1: $2"
            exit 1
            ;;
        esac
        # Or
        if [[ $# -ge 2 && $2 == check_pattern ]]; then
            my_opt_arg=$2
        else
            echo "Invalid argument to $1: $2"
            exit 1
        fi
        shift
        ;;
    *)
        # If we don't have default argument types like files. If that is the case we could do other checks as well.
        echo "Invalid argument: $1"
        # Or
        case $1 in
        /*)
            # It's a file.
            FILES+=("$1")
            ;;
        *)
            # Invalid.
            echo "Invalid argument: $1"
            exit 1
            ;;
        esac
    esac
    shift
done