0

How do I make the below script to accept the first command as one instead of treating the second character as an argument? When I execute this script using ./scriptname -i hello it works as expected but when I use something like ./scriptname -in hello, it echos n as the argument.

#!/bin/bash
run(){
  local OPTIND opt
  while getopts ":i:u:" opt; do
    case $opt in
      i) echo "Typed -i and $OPTARG";iinput="$OPTARG";;
      u)echo "Typed -u";uinput="$OPTARG";;
      \?) help;;
    esac
  done
  shift $((OPTIND -1))
  echo $iinput
  
}
run $@

I was expecting the script to default to calling the help function if its called with anything besides i or u. Currently, I get

Typed -i and n n

When I call the script using ./scriptname -in hello

  • Do you mean "command" or "option"? In your first example, `./scriptname` is the command, `-i` is an option, and `hello` is an argument to that option. – Gordon Davisson Oct 31 '21 at 19:31
  • 2
    The modern convention is for long arguments to use double dashes: `--in`. Most programs interpret `-in` as `-i n` if `-i` takes an argument, or as `-i -n` if it doesn't. It'd be nice to stick to that convention for consistency with other CLI tools. `getopt` without an `s` can parse both short and long options. – John Kugelman Oct 31 '21 at 19:33
  • @JohnKugelman, I read somewhere that getopt is outdated and its recommended to use getops –  Oct 31 '21 at 19:55
  • 1
    I wouldn't call either _recommended_. [BashFAQ #35](https://mywiki.wooledge.org/BashFAQ/035) principally suggests `while`+`case`, and has split off approaches that make unwise tradeoffs (a category in which `getopt` is included) to https://mywiki.wooledge.org/ComplexOptionParsing – Charles Duffy Oct 31 '21 at 20:17
  • 1
    Indeed, the "native" ways to parse options in Bash are not as expressive as those of Python or Perl, and if we end up developing manual parsing code, this can be painful and error-prone… But there's another solution you might be interested in: using a "Bash CLI parser generator" such as [Argbash](https://argbash.readthedocs.io/en/latest/); see e.g. this related SO answer, [Option parser in bash more evolved than getopts](https://stackoverflow.com/a/60022725/9164010). – ErikMD Oct 31 '21 at 21:33

0 Answers0