I am a CentOS user for many years now, but I am still often not sure how the final slash matters in linux commands, e.g.
- tar
- rsync
- mv
- file handling in software/php
What is the actual difference between paths ending and not ending with a slash?
I am a CentOS user for many years now, but I am still often not sure how the final slash matters in linux commands, e.g.
What is the actual difference between paths ending and not ending with a slash?
The answer is "it depends". Many commands don't care, though this changes if the filename given is a symlink to a directory. With a trailing slash, most commands will use the directory the symlink points to, without a trailing slash the command will use the symlink itself.
Some commands like rsync
behave completely differently when there's a trailing slash, for instance giving a trailing slash on the source side of rsync will copy the contents of the directory to the other server in the specified destination location. Without it, the directory itself is created in the destination then the contents are copied over to that. When in doubt, read the documentation (searching for "trailing" is a good start).
cp
and mv
, use of the trailing slash in the destination acts as a bit of a safety net, since it forces the final path component to be interpreted as a directory. Compare mv myfile /some/path
to mv myfile /some/path/
-- if /some/path
does not exist, the first version will create a file, while the second version will fail with an error. If /some/path
exists but is a file, the first version will replace it, while the second version will again fail with an error.
the truth is that it generally depends on the command running
for example rsync with the slash specifically starts at the contents of that directory whereas without the slash it will start at that directory, then its contents. for all intents and purposes for most commands it wont matter but if your not sure you consult the manual for each command eg
man rsync
I'm not 100% sure, how the trailing slash affects cp, mv, rm, though it my experience it doesn't have any practical effect.
e.g.
running
cp -r dir1 dir2
will give you the same result as
cp -r dir1/ dir2
It definitely matters for rsync. In rsync the difference between including and omitting the trailing slash is the difference between syncing the contents of the directory or the directory itself and the contents.
e.g.
rsync -a dir1 dir2
will create a dir1 under dir2
while
rsync -a dir1/ dir2
will create copies of any files in dir1 directly in dir2
It really depends on the program. For instance, find will follow the symlink on a path with a trailaing slash.
mkdir dir1 ln -s dir1 dir2
find dir2 -type d
will return nothing
find dir2/ -type d
will find "dir2/" and continue to recurse through dir1.