laj*_*jos 7 bash command-line-interface mac-osx
在终端中(使用 bash 和 tcsh) cp -r 复制文件夹的内容而不是文件夹的内容,如果文件夹参数在末尾有一个 / 。
鉴于以下结构:
folderA
|-fileA
|-fileB
Run Code Online (Sandbox Code Playgroud)
以下命令将 fileA 和 fileB 复制到目标,而不是将 folderA 复制到目标:
cp -r folderA/ destination
Run Code Online (Sandbox Code Playgroud)
所以它充当
cp -r folderA/* destination
Run Code Online (Sandbox Code Playgroud)
这非常烦人,因为默认情况下 tcsh 中的完成会在文件夹的末尾添加一个 / ,所以如果我忘记删除末尾的 / ,我总是不得不清理。这种行为与我使用过的其他 *nix 不同。
有什么办法可以改变这一点并使 cp -r folderA/ 复制文件夹而不是其内容吗?
有一种情况表明这种行为更有意义(我相信它已被 rsync 使用,即使在 GNU/Linux 上也是如此)。考虑以下情况:
mydir
|-.fileA
|-fileB
Run Code Online (Sandbox Code Playgroud)
这三个说明符的语义都是不同的:
cp -r mydir dest/ # creates dest/mydir, containing both files
cp -r mydir/ dest/ # copies both files directly into dest
cp -r mydir/* dest/ # copies fileB, but not .fileA, directly into dest
Run Code Online (Sandbox Code Playgroud)
我相信这是 BSD 和 GNU 之间差异的一个例子。您可以使用fink安装 GNU 风格的工具(请参阅coreutils 包),但这些工具可能不会保留所有 HFS+ 元数据,因此请谨慎操作。
您可以拦截该命令并去掉尾部斜杠。我将把它留给读者或其他回答者作为练习。
您可以更改制表符完成行为,以便首先不添加斜杠。将以下内容添加到您的~/.tcshrc:
unset addsuffix
Run Code Online (Sandbox Code Playgroud)
通过将以下内容添加到您的 bash 和 misc readline 实用程序中,您可以实现类似的效果~/.inputrc:
set mark-directories off
Run Code Online (Sandbox Code Playgroud)
无需手动删除默认安装中附加的“/”?不幸的是,Apple 的 Darwin手册页上对 cp 的说明并非如此:“如果 source_file 以 / 结尾,则复制目录的内容而不是目录本身。” 所以看来这是达尔文设计的一部分cp。
然而,可以取消设置addsuffixshell 变量,tcsh以便将“/”从添加到目录中删除。最大的缺点是,现在很难仅从完成情况来判断您正在处理的是目录还是文件。为此,请在命令行中键入(或添加到 .tcshrc 中):
unset addsuffix
Run Code Online (Sandbox Code Playgroud)
因为bash您可以使用该mark-directories设置。您可以输入以下内容或将其添加到 .bashrc 中:
bind 'set mark-directories off'
Run Code Online (Sandbox Code Playgroud)
标记目录的使用来源:MacNN 论坛:Hal Itosis