0

I want to pass some interger number using getopt.

This is what I have tried:

if ! options=$(getopt -o n: -l num: -- $@)
then
    exit 1
fi

set -- $options

while [ $# -gt 0 ]
do
    case $1 in
    -n|--num) number=$2 ; shift;;
    esac
    shift
done

echo $number

The Problem is that if I run ./test.sh --num 10 it echos '10' instead of 10 and I cant use it as and integer.

Any Help is welcome!

Malte
  • 91
  • 1
  • 1
  • 8
  • Outputs `10`, not `'10'`, for me. – chepner Mar 07 '22 at 16:18
  • Oops, that's a BSD-vs-GNU issue. GNU `getopt` does produce `'10'`. – chepner Mar 07 '22 at 16:20
  • 1
    At least with this example, using `eval set -- $options` "works", but I don't recall enough about *why* it works to post this as an answer. (One shouldn't use `eval` when one doesn't understand *exactly* how and why it works.) – chepner Mar 07 '22 at 16:25
  • 1
    `getopt` itself is quoting each argument to work with whitespace, but then you need `eval` to strip the resulting quoting as the shell would. You can use `-u` to disable this, but that can cause its own problems. – chepner Mar 07 '22 at 16:26
  • I generally stay away from shell-based argument parsing like this. If I need anything more than what POSIX `getopts` can do, I switch to a language with an easier-to-use library. (For example, Python and its `argparse` module.) – chepner Mar 07 '22 at 16:28
  • Ok, thanks a lot! Really helpful information. – Malte Mar 07 '22 at 16:29
  • 1
    See [BashFAQ/035 (How can I handle command-line options and arguments in my script easily?)](https://mywiki.wooledge.org/BashFAQ/035) for information about how to reliably process command-line options, including long options, in Bash. Note this quote from it: **Do not use getopt(1). Do not even discuss getopt on this page.** – pjh Mar 07 '22 at 19:47
  • 1
    Also see [How do I parse command line arguments in Bash?](https://stackoverflow.com/q/192249/4154375) and [How to get arguments with flags in Bash](https://stackoverflow.com/q/7069682/4154375). – pjh Mar 07 '22 at 19:57
  • Wow, for someone new to bash this is really helpfull! Much appreciated! – Malte Mar 07 '22 at 20:07

0 Answers0