BASH: Copy all files and directories into another directory in the same parent directory

断了今生、忘了曾经 提交于 2019-12-06 13:26:30

问题


I'm trying to make a simple script that copies all of my $HOME into another folder in $HOME called Backup/. This includes all hidden files and folders, and excludes Backup/ itself. What I have right now for the copying part is the following:

shopt -s dotglob

for file in $HOME/*
do
    cp -r $file $HOME/Backup/
done

Bash tells me that it cannot copy Backup/ into itself. However, when I check the contents of $HOME/Backup/ I see that $HOME/Backup/Backup/ exists.

The copy of Backup/ in itself is useless. How can I get bash to copy over all the folders except Backup/. I tried using extglob and using cp -r $HOME/!(Backup)/ but it didn't copy over the hidden files that I need.


回答1:


I agree that using rsync would be a better solution, but there is an easy way to skip a directory in bash:

for file in "$HOME/"*
do
    [[ $file = $HOME/Backup ]] && continue
    cp -r "$file" "$HOME/Backup/"
done



回答2:


try rsync. you can exclude file/directories .

this is a good reference

http://www.maclife.com/article/columns/terminal_101_using_rsync_locally 



回答3:


Hugo,

A script like this is good, but you could try this:

cp -r * Backup/; cp -r .* Backup/;

Another tool used with backups is tar. This compresses your backup to save disk space.

Also note, the * does not cover . hidden files.




回答4:


This doesn't answer your question directly (the other answers already did that), but try cp -ua when you want to use cp to make a backup. This recurses directories, copies rather than follows links, preserves permissions and only copies a file if it is newer than the copy at the destination.



来源:https://stackoverflow.com/questions/20832544/bash-copy-all-files-and-directories-into-another-directory-in-the-same-parent-d

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!