Getopts - space in argument (OPTARG)

Hi,

I want to capture space as well from the argument
eg:

script.ksh -m "Message from xyz" -e "email@xyz.com"
script.ksh -m 'Message from xyz' -e 'email@xyz.com'

I am parsing using getopts, but for option "m" OPTARG is returning only "Message".

try with

 
script.ksh -mMessage\ from\ xyz -e'email@xyz.com'

I tried with escape character as well but within quotes eg.

script.ksh -m "Message\ from\ xyz" -e'email@xyz.com'

Do I need to try without quotes ? I do not have access to system now. I have to check it tomorrow.

Humm, I suspect something else is going on if quotes fail. getopts in ksh is a somewhat complex beast compared to other getopts. Which version of ksh are you using?

Any of the following should work:

script.ksh -m "string with white space"
script.ksh -m 'string with white space'
script.ksh -m string\ with\ white\ space
script.ksh -m string' with'\ "whi"te" "''space

From what i see, i'd assume its more how the argument is set to the variable.

Eg:

while getopts "e:m:": name
do 	case $name in
	m)	var_M="$OPTARG"	;;
	e)	var_E="$OPTARG"	;;
	esac
done

If you leave out the quotes around $OPTARG, it'll catch only the first word of a string.

Hope this helps

1 Like

Here's a script I wrote a long time ago as I was having the same issues.
I'll modify it as necessary when I have getopts problems.

aflag=
bflag=
while getopts :ab:t: opt
do
  case $opt in
    a) aflag=1;;
    b) bflag=1
       bval="$OPTARG";;
    t) tflag=1
       tval="$OPTARG";;
    ?) printf "Usage: %s: [-a] [-b value] args\n" $0
       exit 2;;
  esac
done
if [ ! -z "$aflag" ]; then
  printf "Option -a specified\n"
fi
if [ ! -z "$bflag" ]; then
  printf 'Option -b "%s" specified\n' "$bval"
fi
if [ ! -z "$tflag" ]; then
  printf 'Option -t "%s" specified\n' "$tval"
fi
shift $(($OPTIND - 1))
printf "Remaining arguments are: %s\n" "$*"

Here's the output.

>getopts.sh -b "this is my opt" -t hello\ all
Option -b "this is my opt" specified
Option -t "hello all" specified
Remaining arguments are:

HTH

I think I see the problem, but need a fix.

I am calling a shell script structured as below, though I am placing the arguments in quotes, looks quotes are getting lost through the $* being passed to the function. Can you please suggest a remedy.

parse_cmd () {

   getopts functionality

}


main () {
  parse_cmd $*
}
main $*

Put quotes around $*

If that doesn't work, try "$@" instead, quotes and all. It's special; it passes arguments literally as they came, without splitting and yet still split as they were (despite the quotes).

Yes, double-quoted @ is probably what you want. Also, OP, next time post working code in your first post. It would have saved our volunteers a day's worth of guesses. Even though pseudo-code may shed some light, there is no subsitute for actual code (perhaps a minimized version of your actual script) which demonstrates the problem.

Regards,
Alister