简体   繁体   中英

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

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.

try rsync. you can exclude file/directories .

this is a good reference

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

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM