LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to use getopts to accept multiple parameters for a single option ? (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-use-getopts-to-accept-multiple-parameters-for-a-single-option-752382/)

bittus 09-03-2009 08:18 AM

How to use getopts to accept multiple parameters for a single option ?
 
Hi,

My requirement is to accept multiple parameters using a single option. can anyone help me on this ?

For example :

Suppose a script by name 'solar'. The aim of the script is to accept multiple filenames from the command prompt and search for a string which is also passed thru the command line.

Something like:
./solar -s <string to be searched> -f <file1> <file2> <file3>
I understood that I can use getopts to accept multiple arguments. But not sure how to accept multiple parameters for a single option.

Can anyone help me on this ?

catkin 09-04-2009 01:38 AM

getopts does not support multiple arguments to an option. A comma-separated list of values would be a single argument which you could then parse into individual values in the script.
Code:

./solar -s <string to be searched> -f <file1>,<file2>,<file3>
If the file names may contain whitespace characters then they would have to be quoted on the command line and parsed with IFS set to ",". Some error trapping techniques are also illustrated below
Code:


./solar -f 'my file,my other file'

    while getopts f:s: opt 2>/dev/null
    do
        case $opt in
            s)
                search_string="$OPTARG"
                ;;
            f )
                IFS=',' files=($OPTARG)
                ;;
            * )
                <show short help message>
                \exit 1
        esac
    done

    # Test for extra arguments
    # ~~~~~~~~~~~~~~~~~~~~~~~~
    shift $(( $OPTIND-1 ))
    if [[ $* != '' ]]; then
        <show short help message>
        \exit 1
    fi

    # Test for mandatory options not set
    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    if [[ "$search_string" == '' -o "$files" == '' ]]; then
        <show short help message>
        \exit 1
    fi

EDIT:
Code:

IFS=',' files=($OPTARG)
is dangerous; it leaves $IFS set to ",". See this post for an explanation.


All times are GMT -5. The time now is 05:34 PM.