2

This question already has an answer here:

I am trying to process a command line using getopts in bash. I have to pass three arguments after -w option. For example, -w 1 do loop. It should print one line before and after each line from loop that contains the pattern do. This is the code I have now:

#!/bin/bash
file=`ls | grep ^$1$`
pattern=`cat $file |grep -B$2 -A$2 $3`
while getopts":w:" opt
do
case $opt in
    w) $2=$OPTARG ; pattern=$OPTARG ; file=$OPTARG ;array=($OPTARG)
    ;;
    *)echo " usage: -w <pattern>"
    exit 1
    ;;
esac
done

echo "${#array[@]}"
echo "line: $2, pattern: $pattern, file: $file"

Is there anyway to retrieve the three variables from one flag?

marked as duplicate by jimmij, Jeff Schaller, Stephen Rauch, user259412, DarkHeart Dec 18 '17 at 2:54

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3

Only one argument can be passed to an option, but you may specify a,b,c and later temporarily set IFS to ',' and use read to split the argument a,b,c into three words.

For example:

$ OPTARG="1,do,loop"
$ IFS=, read n patt file <<<"$OPTARG"
$ echo $n; echo $patt; echo $file
1
do
loop

Not the answer you're looking for? Browse other questions tagged or ask your own question.