Tuesday Tiny Techie Tip

Dealing with arguments starting with "-"

Almost all UNIX utilities accept flags indicated by a leading minus sign (e.g., "-rf"). This makes it easy to program the argument parsing portion of commands, you just look through the arguments for stuff starting with a minus to find the flags.

However, if you need to pass something beginning with a minus as an actual argument, it gets maddening:


[look for the string "-rf" in files in the current directory]
% grep -rf *
grep: illegal option -- r
grep: illegal option -- f
Usage: grep -blcnsviwh [ -e ] pattern file . . .
% grep '-rf' *
grep: illegal option -- r
grep: illegal option -- f
Usage: grep -blcnsviwh [ -e ] pattern file . . .
% grep \-rf *
grep: illegal option -- r
grep: illegal option -- f
Usage: grep -blcnsviwh [ -e ] pattern file . . .

Most UNIX commands support a special flag to indicate that the remainder of the command line does not contain any more option flags. The special flag is two minus signs together ("--"):


% grep -- -rf *

The other time this problem comes up is if you accidentally create a file with a minus sign as the first character and then want to delete it:


% touch -- -foo
% ls
-foo    bar
% rm -foo
usage: rm [-rif] file ...
% rm -- -foo
usage: rm [-rif] file ...

Uh oh! minus-minus didn't work with rm(1). Now what?

Here we need to use some other trick to keep the minus from being interpreted as a flag indicator. The easiest way is to more completely specify the path to the file so the minus isn't hanging out there as the first character:


% rm ./-foo

Some versions of rm (SunOS in particular), accept a single unadorned minus as the same signal as two minuses together, so in SunOS land, this will also work:


% rm - -foo


Tuesday Tiny Techie Tip -- 4 March 1997
Forward to (03/11/97)
Back to (02/25/97)
Written by Jeff Youngstrom

Up to the TTTT index

Tuesday Tiny Techie Tips are all © Copyright 1996-1997 by Jeff Youngstrom. Please ask permission before reproducing any of this material.