I'm new to working in the shell and the usage of these commands seems arbitrary. Is there a reason one flag has a single dash and another might have a double dash?
I'm new to working in the shell and the usage of these commands seems arbitrary. Is there a reason one flag has a single dash and another might have a double dash?
A single hyphen can be followed by multiple single-character flags. A double hyphen prefixes a single, multicharacter option.
Consider this example:
In this example,
-czf
specifies three single-character flags:c
,z
, andf
.Now consider another example:
In this case,
--exclude
specifies a single, multicharacter option namedexclude
. The double hyphen disambiguates the command-line argument, ensuring thattar
interprets it asexclude
rather than a combination ofe
,x
,c
,l
,u
,d
, ande
.It all depends on the program. Usually "-" is used for 'short' options (one-letter, -h), and "--" is used for "long"(er) options (--help).
Short options can usually be combined (so "-h -a" is same as "-ha")
source
It's really a convention. However, it can aid parsers to know more efficiently about options passed to the program. Besides, there are neat utilities that can help parsing these commands, such as
getopt(3)
or the non-standardgetopt_long(3)
to help parse the arguments of a program.It is nice, for we can have multiple short options combined, as other answers say, like
tar -xzf myfile.tar.gz
.If there was a "lisa" argument for
ls
, there would probably have a different meaning to typels -lisa
thanls --lisa
. The former are thel
,i
,s
, anda
parameters, not the word.In fact, you could write
ls -l -i -s -a
, meaning exactly the same asls -lisa
, but that would depend on the program.There are also programs that don't obey this convention. Most notably for my sight,
dd
andgcc
.short options can be combined into a single argument;
If we allow long options with single dash, it causes ambiguity. To resolve this we use double dash for long options.
Another case is when a script calls another program, it may be necessary to separate the options for the first script from those passed to the second program. For example, you can write a bash function to parse the command line, similar to the function below. Then use a command line similar to the following. In this case the double dashes keep the options for each program separated and allows the built-in parser's error handling to work as intended. Of course, there may special cases that would need to be handled.