首页 > 解决方案 > 将脚本选项/参数分配给变量并手动循环

问题描述

我正在使用BashFAQ 手动循环的变体,我想将其转换为函数并将参数分配给局部变量,但我无法找出正确的语法。这是我所拥有的:

function parseArguments() {
    local arguments=( "$@" )

    while :; do
        case ${1:-} in
            -d|--debug)
                set -o xtrace
                # [...more stuff...]
                ;;
            -p|--prompt)
                IsPromptEnabled=true
                ;;
            --)
                shift
                break
                ;;
            -?*)
                error ${LINENO} "\"${1:-}\" is an unknown option" 1
                ;;
            *)
                break
        esac

        shift
    done
}

parseArguments "$@"

这可以正常工作,直到我尝试用 from 的值替换$1循环中的值arguments${arguments[0]}以及我能想到的所有其他变体都失败了,我想了解原因(并找出解决方案)。

标签: bash

解决方案


You should loop over the array

function parseArguments() {
    local arguments=( "$@" )

    for a in "${arguments[@]}"
    do
        case ${a:-} in
            -d|--debug)
                set -o xtrace
                # [...more stuff...]
                ;;
            -p|--prompt)
                IsPromptEnabled=true
                ;;
            --)
                # shift
                break
                ;;
            -?*)
                error ${LINENO} "\"${a:-}\" is an unknown option" 1
                ;;
            *)
                break
        esac

        shift
    done
}

parseArguments "$@"

推荐阅读