What's the difference between - (one hyphen) and -- (two hyphens) in a command? [duplicate]

Both seem to be flags but what is the difference?


Solution 1:

Generally:

  • - means to read the argument/content from STDIN (file descriptor 0)

  • -- means end of command options, everything follows that are arguments

Why needed:

About -:

$ echo foobar | cat -
foobar

Although cat can read content from STDIN without needing the -, many commands need that and their man pages mention that explicitly.

Now about --, I have created a file -spam, let's cat the file:

$ echo foobar >-spam  

$ cat -spam         
cat: invalid option -- 'p'
Try 'cat --help' for more information.

$ cat -- -spam      
foobar

Without --, cat takes s, p, a, m all as it's options as they follow -, -- explicitly indicates the end of option(s), after that -spam is taken as a file name.

Solution 2:

  • -- is the long name version
  • - is the short name version

Have a look at man ls and some of the options:

-a, --all : do not ignore entries starting with .
-A, --almost-all : do not list implied . and ..
-b, --escape : print C-style escapes for nongraphic characters
-B, --ignore-backups : do not list implied entries ending with ~

They are the same but some prefer the short, some the long versions.

And both are there for compatibility. Removing an option breaks software.


Not every command follows this this. As @ Bakuriu mentions in comment: a command like find has what you can consider "long names" with 1 hyphen.


In regards to coding there is something to note too:

  • Bash's getopts does not support long names.
  • The getopt from the GNU utils does.