1. Overview

In this tutorial, we're going to examine the use of the double-dash in shell commands. We'll take a look at what it does and when we might need it.

2. What Does It Do?

A double-dash in a shell command signals the end of options and disables further option processing. Let's see this in action using the grep command.

Imagine a scenario where we'd like to search for the occurrences of hello in the file data.txt:

$ grep hello data.txt

This command outputs all occurrences of the string hello from the specified file. But, what if instead of hello, we want to find all occurrences of "--hello"?

If we use the same approach, we'll receive an error:

$ grep "--hello" data.txt
grep: unrecognized option '--hello'

That's because grep treats "--hello" as a multi-character command option. To overcome that, we will need to use a double-dash (--). Anything that comes after it will be treated as a positional parameter:

$ grep -- --hello data.txt

3. When Is It Needed?

We need to use a double-dash anytime our non-option arguments start with a hyphen. If we don't terminate option processing, commands will try to interpret non-option arguments as options, and most likely fail.

We already saw what happens when we provide grep with a pattern that starts with a hyphen. It's not always this obvious, though.

Sometimes, we don't have full control over the parameters. For example, a parameter can be supplied to a command using an environment variable:

$ grep $PATTERN data.txt

If the environment variable PATTERN content is "--hello", the grep command will treat the pattern as a command option, and fail. Instead, we should use a double-dash:

$ grep -- $PATTERN data.txt

We can run into a similar situation when deleting files. For example, let's say we have a folder full of text files. We could delete them using rm with a wildcard:

$ rm *.txt

But if any of the file names start with a hyphen, the command will fail because the file name is going to be treated as a command option. To solve that, we have to use a double-dash:

$ rm -- *.txt

4. Not Supported by All Commands

Unfortunately, not all commands support the double-dash feature.

For example, let's take a look at the echo command in Bash. If we would like to output the string "-n" using echo, we could try using a double-dash to terminate the option processing:

$ echo -- "-n"
-- -n

The version of echo bundled with Bash will output the double-dash as well. However, if we try to run the command without a double-dash, we'll receive no visible output. That's because "-n" is treated as an option that instructs echo not to print the trailing newline character.

5. Conclusion

In this tutorial, we looked at what the double-dash in shell commands does. We covered when we might need it, and learned that not all commands support this feature.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.