What's the difference between
cd abc/xyz/
and
cd abc/xyz
What's the importance of /
at the end? Which is the right way of using it? Because both seem to work properly.
What's the difference between
cd abc/xyz/
and
cd abc/xyz
What's the importance of /
at the end? Which is the right way of using it? Because both seem to work properly.
The difference may be minor in the cd
example you provided, but beware when you mv
files.
For example if you want to move several files to another directory, and you type
for i in *.mp3 ; do mv $i dest ; done
Forgetting the trailing slash, then each of the files moved will overwrite a file called dest
(the first will actually create a file called dest
if it doesn't already exist). The result is that all files except the last are overwritten with the last file, and it's now called dest
.
To move to a directory, you must specify the trailing /
for i in *.mp3 ; do mv $i dest/ ; done
One side effect of the slash is that if the directory doesn't exist, you'll get an error message.
mv
gets resolved in practice. Likewise the issue with rsync
.
Jan 18, 2010 at 13:40
cd abc/xyz
Is correct, since "abc/xyz" refers to 'the "xyz" entity in the "abc" directory'. When you type
cd abc/xyz/
it refers to 'The "" entity in the "xyz" directory in the "abc" directory'. The "" (empty string) entity gets automatically translated to ".", which is the "current" directory, which in this case is the "xyz" directory. So it all works out to the same thing.
(Some people feel that directories "must" have a slash appended. They are mistaken.)
cd abc/xyz/
is the correct way of doing it. But if you specify
cd abc/xyz
and if cd figures out that xyz is a directory, it assumes the presence of the trailing /
They are identical. The string is treated by the filename operators as a "path" which is an abstraction, and each path is associated with a basename and another path, the dirname. Two paths are identical if each of these are the same string. For your example:
cas var$ dirname abc/xyz; basename abc/xyz abc xyz cas var$ dirname abc/xyz/; basename abc/xyz/ abc xyz
Note that, while some programs treat strings identically, including all the usual UNIX utilities, if they are the same paths, there are others that do care about trailing slashes. The most important of these is rsync
.
Postscript From the POSIX spec, Pathname Resolution:
A pathname that contains at least one non-slash character and that ends with one or more trailing slashes shall be resolved as if a single dot character ( '.' ) were appended to the pathname.
abc/xyz/
is actually interpreted (under POSIX) as abc/xyz/.
. (Teddy made this point in his answer as well, but thanks for providing a source.)
Jan 18, 2010 at 13:36