0

I am working on a bash script, and I decided to use getopts to get the options, but the loop I used doesn't work! Could someone please help me?

while getopts "u:p:k:s:t:c:l:" flag
do
    echo $flag
    case "$flag" in
        k)  APIKEY="$OPTARG"
            ;;
        s)  APISECRET="$OPTARG"
            ;;
        u)  USERNAME="$OPTARG"
            ;;
        p)  PASSWORD="$OPTARG"
            ;;
        t)  TITLE="$OPTARG"
            ;;
        c)  CATEGORY="$OPTARG"
            ;;
        l)  LANGUAGE="$OPTARG"
            ;;
 esac
done
shift $((OPTIND-1))

None of the above variables are being set.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
Danogentili
  • 664
  • 7
  • 13
  • How do you verify that the variables have been set? When I add `echo $CATEGORY` and run with `sample.sh -c Test`, it outputs `Test`. – choroba Jun 21 '15 at 08:05
  • In my script it doesn't work. https://github.com/danog/DailyMotionUpload/raw/master/dmUpload.sh – Danogentili Jun 21 '15 at 08:07
  • 1
    How do you passing your arguments? Give us command line example – Samuel Jun 21 '15 at 08:33
  • On an unrelated note: for displaying usage, you could have used `cat << EOF` instead of `echo`... :-) – anishsane Jun 21 '15 at 12:38
  • What do you mean by the loop doesn't work? Are you sure that variables are not populated properly? There could be errors in the code after the loop. Try debugging the code. Change shebang to `#!/bin/bash -vx`. For testing Skip the code after getopts loop by adding an unconditional exit 0 & print the variables collected via getopts loop. Or just call `env` after the `getopts` loop. – anishsane Jun 21 '15 at 12:39
  • Thanks anishane, now it works (thanks to choroba's answer)! – Danogentili Jun 21 '15 at 13:54

1 Answers1

1

Don't use = with getopts and short options. Also, if you want to supply "non-options", e.g. file names (video.mp4 in your case), they should come last, not before the options (and you have to change the code accordingly); or you can process them (and shift) before you start the options loop.

dmUpload.sh -u USERNAME -p PASS -k KEY -s SECRET -c CAT -t TILE -l LANG video.mp4
choroba
  • 231,213
  • 25
  • 204
  • 289
  • It seems OP would like to use positional arguments as optional list of tags. Then you should save the first option as `infile` and do `shift` before processing with `getopts`. – leesei Jun 21 '15 at 08:17