没有隐藏文件的 cp-r

我有两个目录,一个是空的。

第一个目录有许多带有隐藏文件的子目录。当我的 cp -r内容从第一个目录到第二个目录,隐藏的文件也得到复制。有办法逃脱吗?

56280 次浏览

You can do

cp -r SRC_DIR/* DEST_DIR

to exclude all .files and .dirs in the SRC_DIR level, but still it would copy any hidden files in the next level of sub-directories.

You can use rsync instead of cp:

rsync -av --exclude=".*" src dest

This excludes hidden files and directories. If you only want to exclude hidden directories, add a slash to the pattern:

rsync -av --exclude=".*/" src dest

rsync has "-C" option

http://rsync.samba.org/ftp/rsync/rsync.html

Example:

rsync -vazC  dir1 dir2

I came across the same need when I wanted to copy the files contained in a git repo, but excluding the .git folder, while using git bash.

If you don't have access to rsync, you can replicate the behavior of --exclude=".*" by using the find command along with xargs:

find ./src_dir -type f -not -path '*/.*' | xargs cp --parents -t ./dest_dir

To give more details:

  • find ./src_dir -type f -not -path '*/.*' will find all files in src_dir excluding the ones where the path contain a . at the beginning of a file or folder.
  • xargs cp --parents -t ./dest_dir will copy the files found to dest_dir, recreating the folder hierarchy thanks to the --parents argument.

Note: This will not copy empty folders. And will effectively exclude all hidden files and folders from being copied.

Link to relevant doc:

https://linux.die.net/man/1/cp

https://linux.die.net/man/1/find