我正在尝试使用 getopts 使我的脚本能够接受命令行参数,例如 -s "gil.sh 123 。因为它不支持长名称的命令行参数,我有一个函数,它接受参数,并将长版本(在这种情况下 --script)的每次出现更改为短版本(-s),然后才 getopts 得到叫。

问题是,如果它包含空格(在这种情况下为“gil.sh 123”),那么我无法获得第二个函数将其作为具有 2 个成员的数组,在这种情况下,我得到的是数组 (-s gil.sh 123) 而不是 (-s "gil.sh 123"),这是什么我发送了函数。

这是我的代码:

#!/bin/bash
#change long format arguments (-- and then a long name) to short format (- and then a single letter) and puts result in $parsed_args
function parse_args()
{
    m_parsed_args=("$@")
    #changes long format arguments (--looong) to short format (-l) by doing this:
    #res=${res/--looong/-l}
    for ((i = 0; i < $#; i++)); do
        m_parsed_args[i]=${m_parsed_args[i]/--script/-s}
    done
}

#extracts arguments into the script's variables
function handle_args()
{
    echo "in handle_args()"
    echo $1
    echo $2
    echo $3
    while getopts ":hno:dt:r:RT:c:s:" opt; do
        case $opt in
            s)
                #user script to run at the end
                m_user_script=$OPTARG
                ;;
            \?)
                print_error "Invalid option: -$OPTARG"
                print_error "For a list of options run the script with -h"
                exit 1
                ;;
            :)
                print_error "Option -$OPTARG requires an argument."
                exit 1
                ;;
        esac
    done
}

parse_args "$@"
handle_args ${m_parsed_args[@]}

(这段代码显然比原来的代码短,它有更多的替换和参数类型,我只留下了一个)

我这样调用脚本:./tmp.sh -s "gil.sh 123",我可以看到在 parse_args 之后变量 m_parsed_args 是一个有 2 个成员的数组,但是当我将它发送到 handle_args 时,该数组有 3 个成员,所以我不能给变量 m_user_script 正确的值,我希望它得到(“gil.sh 123”)

最佳答案

为什么不对 m_parsed_args 数组使用双引号?

handle_args "${m_parsed_args[@]}"

关于bash - 将带空格的数组传递给 Bash 函数以充当其参数列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18981748/

10-14 18:43
查看更多