linux - 复制文件夹时,我应该在源和目标后面加上尾部斜杠吗

标签 linux unix cp

我要复制:

  • 此文件夹:ajax (/home/thej/public_html/JC/ajax)。
  • 进入此文件夹:/home/thej/public_html/demo/conf/。最终结果将是/home/thej/public_html/demo/conf/ajax

我知道 cp 命令应该是这样的:

cp -r /home/thej/public_html/JC/ajax /home/thej/public_html/demo/conf

我的问题是:

  1. 我应该把 / 放在 ajaxajax/ 之后吗?

  2. 我应该把/放在confconf/之后吗?

我在网上搜索了一下,有些放了“/”,有些没有,所以真的很困惑。

最佳答案

源目录没有尾部斜杠

不应该在源目录中放置一个尾部斜杠:

该点与 cp 相关 - 也与 mv 相关,后者更重要

我将引用手册中的警告 - 请注意,它未在手册页中找到,但在信息页中找到 info coreutils 'mv invocation':

Warning: Avoid specifying a source name with a trailing slash, when it might be a symlink to a directory. Otherwise, 'mv' may do something very surprising, since its behavior depends on the underlying rename system call. On a system with a modern Linux-based kernel, it fails with 'errno=ENOTDIR'. However, on other systems (at least FreeBSD 6.1 and Solaris 10) it silently renames not the symlink but rather the directory referenced by the symlink.

在目标目录上使用尾部斜杠

如果你想将文件和目录移动到一个目录中,你应该在目标目录中添加一个尾部斜杠。
只要一切顺利,它不会改变任何东西。
但它可以避免导致数据丢失或更改的常见错误:

如果将文件移动到目录中,有两件事可能会出错:
您可能拼错了目标目录名称的最后一个组成部分,例如一个错误的字符。 这两种情况可能会发生两种情况:

  • 如果拼错的名字存在:

    • 文件将重命名为拼写错误的名称

    • 它被移动到预期目的地的父目录

    • 所以它最终既不是它本来的样子,也不是你期望它去的地方。

  • 如果拼写错误的名称确实存在,并且是一个文件:

    • 文件将覆盖目标父目录中名称拼写错误的文件。

    • 同样,您不会发现它曾经存在或应该存在的位置:它只是消失了。

如果您在目标目录上使用尾部斜杠,则两种情况都会被阻止:

这使得 mv 不会像通常那样将其用作文件名。相反,mv 只是给出一个错误:

mv: failed to access ‘foo/’: Not a directory

自动删除斜杠

cpmv 有一个特殊选项,可以通过始终从 src 目录中删除斜线来降低风险:

Some GNU programs (at least `cp' and `mv') allow you to remove any
trailing slashes from each SOURCE argument before operating on it.  The
`--strip-trailing-slashes' option enables this behavior.

   This is useful when a SOURCE argument may have a trailing slash and
specify a symbolic link to a directory.  This scenario is in fact rather
common because some shells can automatically append a trailing slash
when performing file name completion on such symbolic links.  Without
this option, `mv', for example, (via the system's rename function) must
interpret a trailing slash as a request to dereference the symbolic link
and so must rename the indirectly referenced _directory_ and not the
symbolic link.  Although it may seem surprising that such behavior be
the default, it is required by POSIX and is consistent with other parts
of that standard.

关于linux - 复制文件夹时,我应该在源和目标后面加上尾部斜杠吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18158248/

相关文章:

Linux CP 使用 AWK 输出

linux - Samba 4 的帐户锁定策略

c++ - 在信号处理程序中设置标志

python - 将执行哪个版本的程序?是/usr/bin 里的还是/usr/local/bin 里的?

bash - 比较以获取第二个文件中更改的行

linux - BASH 复制除一个文件以外的所有文件

c - 定期打印信息的 Linux 设备驱动程序

linux - 如果列表不为空,list_empty 返回 1(非零)

linux - 无法使用 awk 提取 fastboot 命令

linux - 复制或 move 时合并源路径和目标路径以避免长路径重复