Question

I am trying to use getopts to make my script be able to take command line arguments, like -s "gil.sh 123. Because it does not support command line arguments with long names, I have a function that takes the arguments, and changes every appearance of the long version (in this case --script) to the short version (-s) and only then getopts gets called.

The problem is that if it contains spaces (in this case "gil.sh 123") then I cannot get the second function to take this as an array with 2 members, in this case i get the array (-s gil.sh 123) instead of (-s "gil.sh 123") which is what I sent the function.

Here is my code:

#!/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[@]}

(This code is obviously shorter than the original which has many more substitutions and types of arguments, i only left one)

I call the script like this: ./tmp.sh -s "gil.sh 123" and I can see that after parse_args the variable m_parsed_args is an array with 2 members, but when I send it to handle_args the array has 3 members, so I cannot give the variable m_user_script the correct value that i want it to get ("gil.sh 123")

Était-ce utile?

La solution

Why do not you use double quotes for the m_parsed_args array?

handle_args "${m_parsed_args[@]}"
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top