0

I'm trying to use getopts like this:

#!/bin/bash

while getopts "i" option
do
 case "${option}"
 in
 i) INT=${OPTARG};;
 esac
done
echo "$INT"

But it prints $INT only if i use getopts "i:". If I understand correctly, the colons in the optstring mean that values are required for the corresponding flags. But I want to make this flag optional. Can anyone explain why the script acts like this and how can I fix it?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
kusayu
  • 93
  • 6
  • 1
    The presence of the colon means an option argument is required. The absence of a colon means no option argument is expected at all. The Bash manual on [`getopts`](http://www.gnu.org/software/bash/manual/bash.html#index-getopts) doesn't support optional arguments. For that, you'd need GNU `getopt` (with a whole lot of different semantics). – Jonathan Leffler Aug 25 '17 at 21:22
  • @JonathanLeffler ah, thank you very much. I think i need to delete my question because it can't be answered. – kusayu Aug 25 '17 at 21:29
  • See related question [Using `getopts` in Bash shell script to get long and short command line options](https://stackoverflow.com/questions/402377/using-getopts-in-bash-shell-script-to-get-long-and-short-command-line-options). It's not a direct duplicate, but contains useful information. – Jonathan Leffler Aug 25 '17 at 21:42
  • There's a version of an extended `getopt` command available from http://frodo.looijaard.name/project/getopt. – Jonathan Leffler Aug 25 '17 at 21:49

1 Answers1

1

You cannot make it (bash getopts) optional like that. The "getopts" does not support mandatory or optional options. You would need to code for that. And if a ":" is specified then there needs to be an argument to that option. There is no way to around it.

The following code snippets shows how to check for mandatory arguments.

# Mandatory options
arg1=false;
..
...
case "${option}"
 in
 i) INT=${OPTARG}; arg1=true;
 ;;
 esac
 if  ! $arg1;
 then
  echo -e "Mandatory arguments missing";
  # assuming usage is defined
  echo -e ${usage};
  exit 1;
fi
Khanna111
  • 3,627
  • 1
  • 23
  • 25