Search code examples
bashshellwildcardgetoptquoting

How to avoid expansion of single-quoted text in the `eval set... "$@"` for getopt?


I'm using the conventional pattern for performing parameters decoding via getopt:

function mytest {
  eval set -- `getopt --options h --long help -- "$@"`
  echo "1:$1 2:$2"
}

But when I pass a single quoted string, it is actually expanded, for example:

$ mytest 'x * z'
1:-- 2:<list of files from current dir>

Strangely, it seems that only the specific structure '<string> * <other_strings>' triggers the behavior; similar structures don't:

$ mytest '* z'
1:-- 2:* z
$ mytest 'x *'
1:-- 2:x *

How can I perform evaluation as intended?


Solution

  • Quote your expansions to prevent globbing:

    function mytest {
       eval set -- "`getopt --options h --long help -- "$@"`"
       echo "1:$1 2:$2"
    }