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

时间:2013-09-24 12:33:33

标签: bash shell getopt

我正在尝试使用getopts使我的脚本能够获取命令行参数,例如-s "gil.sh 123。因为它不支持带有长名称的命令行参数,所以我有一个接受参数的函数,并将长版本(在本例中为--script)的每个外观更改为短版本(-s),然后才更改{{ 1}}被调用。

问题是,如果它包含空格(在本例中为“gil.sh 123”),那么我无法得到第二个函数将其作为包含2个成员的数组,在这种情况下我得到数组{{1}而不是我发送函数的getopts

这是我的代码:

(-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"是一个包含2个成员的数组,但是当我将它发送到{{1}时这个数组有3个成员,所以我不能给变量parse_args提供我想要的正确值(“gil.sh 123”)

1 个答案:

答案 0 :(得分:5)

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

handle_args "${m_parsed_args[@]}"
相关问题