Subject: Re: bug#11271: dirname /home/dir/
From: Eric Blake <[email-masked]>
To: Kevin Huanpeng Du <[email-masked]>
Cc: [email-masked]
Date: Wed, 18 Apr 2012 11:35:23 -0600
List-Id: <debbugs-submit.debbugs.gnu.org>

tag 11271 notabug
thanks

On 04/18/2012 05:01 AM, Kevin Huanpeng Du wrote:
> Hi,
> i find dirname dirname strip a dir name when a string with out a filename.
> 
> ₤ dirname /dir/file
> ₤ /dir
> ₤ dirname /dir/subdir/
> ₤ /dir # is this right? subdir is a not a file.

Thanks for the report.  However, this is not a bug.  POSIX requires this
behavior.  In POSIX parlance, a "file" is any entity that can be
referenced by name as a member of a directory.  There are multiple types
of files: regular files, block device files, character device files,
sockets, and important to your case, subdirectories.  Only
subdirectories may have a trailing slash, but the point remains that
even without the trailing slash, 'subdir' is a file (of type directory,
rather than the more typical type regular file), which can be referenced
by name from the directory '/dir'.

The POSIX-mandated algorithm for the dirname executable is to strip
trailing slashes _before_ removing the trailing file name element,
precisely for usage like this:

http://pubs.opengroup.org/onlinepubs/9699919799/utilities/dirname.html

1    If string is //, skip steps 2 to 5.

2    If string consists entirely of <slash> characters, string shall be
set to a single <slash> character. In this case, skip steps 3 to 8.

3    If there are any trailing <slash> characters in string, they shall
be removed.

4    If there are no <slash> characters remaining in string, string
shall be set to a single <period> character. In this case, skip steps 5
to 8.

5    If there are any trailing non- <slash> characters in string, they
shall be removed.

6    If the remaining string is //, it is implementation-defined whether
steps 7 and 8 are skipped or processed.

7    If there are any trailing <slash> characters in string, they shall
be removed.

8    If the remaining string is empty, string shall be set to a single
<slash> character.

And according to that algorithm, even though '/dir/subdir',
'/dir/subdir/' and '/dir/subdir/.' all resolve to the same location in
the file system, using dirname on the first two gives '/dir' while using
'dirname /dir/subdir/.' gives '/dir/subdir'.

-- 
Eric Blake   [email-masked]    +1-919-301-3266
Libvirt virtualization library http://libvirt.org