Many Linux commands accept command-line options and positional parameters. The grep command searches for a pattern in a given file. Its 2 positional parameters are the pattern and the filename. It accepts options such as -i which specifies that the search is case insensitive.
An interesting scenario is when a positional parameter has a value starting with a dash ('-'). This makes the parameter indistinguishable from an option. For example, you try to grep the string -tea in a given file.
$ grep -i '-tea' test.txt grep: invalid option -- 't' Usage: grep [OPTION]... PATTERN [FILE]... Try 'grep --help' for more information.
The -tea is interpreted as an option. Consequently, the command failed.
To solve the problem, insert the double dash (--) on the command line to mark the end of all options. Everything that come after the -- marker are interpreted as positional parameters.
$ grep -i -- '-tea' test.txt Beverages -tea and coffee- are served.
Anther example scenario for using the double dash is the deleting of a file with a pesky file name. Suppose you want to delete a file named '-a'.
$ rm -a rm: invalid option -- 'a' Try `rm --help' for more information.
Enter -- to mark where the positional parameters start.
$ rm -- -a
1 comment:
Using escape characters:
grep -i "\-a" prueba
Post a Comment