将带有空格的数组传递给Bash函数以充当其参数列表

gil*_*_bz 3 bash shell getopt

我试图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[@]}
Run Code Online (Sandbox Code Playgroud)

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

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

cho*_*oba 5

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

handle_args "${m_parsed_args[@]}"
Run Code Online (Sandbox Code Playgroud)