3

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?

1
  • I just found out about this feature today! I accepted a few answers of older questions, it's still only 8% though?
    – ujjain
    Jun 12, 2011 at 15:09

4 Answers 4

5

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).

1
  • 2
    Using commands like 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.
    – larsks
    Jun 12, 2011 at 19:02
0

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
0

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

0

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .