Say I have a command that takes flags and arguments, like this:

mycommand --foo bar arg1 arg2

(The foo flag has a value of "bar".)

But what if the foo flag can optionally be supplied with no argument?

mycommand --foo arg1 arg2

How do I prevent arg1 being considered the value for the foo flag?

  • 1
    I'm voting to move this question to Unix & Linux since it's more about how unix works than about systems administration. In other words, the close vote currently on your question is not about actually closing but about moving.
    – Jenny D
    Jun 29, 2016 at 14:13

3 Answers 3


The most common used idiom in Unix to separate the command line flags from the rest of the arguments is to use a double dash (--).

If the utility uses the C library function getopt() (either directly or indirectly), the double dash will signal the end of the command line options, and getopt() will end its parsing of the command line.

This is from the getopt(3) manual on OpenBSD:

The interpretation of options in the argument list may be cancelled by the option ‘--’ (double dash) which causes getopt() to signal the end of argument processing and return -1.

This is why the correct way to delete a file called -f is

$ rm -- -f

for example.

It is likely that your shell implements the built-in getopts command with a call to this library function.

IMHO, it's nice to know how to use getopts in shell scripts, and getopt() in C programs. It's not very difficult, and it makes life a lot easier when you write the command line parsing code of your project.

There is also a getopt_long() available in some C libraries, for parsing "long options" (--option=value). This, however, is an extension (no pun intended).


Consider something like:

mycommand --foo=bar arg1 arg2

Requiring =<someval> when assigning a value to the flag would remove ambiguities.

It is clear this is a different case where the value is not specified:

mycommand --foo arg1 arg2

There's no general answer to this. It depends entirely on how mycommand interprets its arguments. The ambiguity would be removed, e.g., if mycommand only accepted a limited number of values for foo which can never occur as argument values, so an omitted foo value could be easily detected by checking if the next command-line parameter is an acceptable value for foo or not.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .