Why does grep sometimes return directories with two slashes

grep

I just ran grep -ri foo someDir/

I got back

someDir//foo/bar/baz: onDelete() {

Does the double forward slash just mean that everything to the left of it was in the dir argument you provided to grep?

Best Answer

When you run the command:

grep -r <pattern> <directory>

it prints all the filenames as <directory>/<filename>. If you put a slash at the end of <directory>, it will be included in that, so you end up with a double slash.

The code could have been smart enough to notice when the original directory name ends with / and omit it when printing filenames, but they didn't bother. I think the only special case it makes is for the root directory, e.g.

grep -r pattern /

will print /foo/bar/baz rather than //foo/bar/baz. This is because POSIX specifies that a sequence of slashes is treated equivalently to a single slash except that two slashes at the beginning have implementation-dependent meaning (this is because some network file system mechanisms made use of syntax like //server/pathname). See How does Linux handle multiple consecutive path separators (/home////username///file)?

Related Question