18

I'm looking for a way to handle arguments containing blank spaces that has to be parsed by shell getopts command.

while getopts ":a:i:o:e:v:u:" arg
  do
  echo "ARG is: $arg" >> /tmp/submit.log
  case "$arg" in
  a) arg1="$OPTARG" ;;
  i) arg2="$OPTARG" ;;
  o) arg3="$OPTARG" ;;
  ...
  u) argn="$OPTARG" ;;
  -) break ;;
  \?) ;;
  *) echo "unhandled option $arg" >> /tmp/submit.log ;;
  ?) echo $usage_string
     exit 1 ;;
  esac
done

Now if -u has argument like "STRING WITH WHITE SPACE" than just the first part of the string is triggered and the while loop doesn't go to the end.

many thanks.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
DrFalk3n
  • 4,926
  • 6
  • 31
  • 34
  • 2
    that's not generally possible. you need to quote the arguments to your script properly, just like you did in your post. – Mat May 16 '11 at 14:12
  • Thanks Mat you pointed out the fault – DrFalk3n May 17 '11 at 08:27
  • PS: This bash getopts is a nice alternative to man getopt on Darwin. – Necro Apr 08 '13 at 18:37
  • 1
    You need to be a bit cautious when you are using $variable in script, if you have a variable like filename="some file.txt" and run a simple 'ls $filename', bash will raise an error, because the bash will run the ls command after replacing the variable. So the actual command is 'ls some file.txt' and bash will complain that it can't find 'some'. – mehdi Mar 18 '23 at 14:26

2 Answers2

42

a trap for young players (ie me!)

beware a line like this:

main $@

what you really need is:

main "$@"

otherwise getopts will mince up your options into little pieces

http://www.unix.com/shell-programming-scripting/70630-getopts-list-argument.html

Nickolay
  • 31,095
  • 13
  • 107
  • 185
ErichBSchulz
  • 15,047
  • 5
  • 57
  • 61
13

As Mat notes, your script fragment is already correct. If you're invoking your script from a shell, you need to quote arguments properly, e.g.

myscript -u "string with white space"
myscript -u 'string with white space'
myscript -u string\ with\ white\ space
myscript -u string' w'ith\ "whi"te" "''space

Requiring these quotes is not a defect in your script, it's the way the calling shell works. All programs, scripts or otherwise, receive arguments as a list of strings. The quotes in the calling shell are used to sort these arguments into separate “words” (list elements). All the calls above (made from a unix shell) pass a list of three strings to the script: $0 is the script name (myscript), $1 is -u and $2 is the string string with white space.

Community
  • 1
  • 1
Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254