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

StackOverflow https://stackoverflow.com/questions/20832544

  •  22-09-2022
  •  | 
  •  

質問

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.

役に立ちましたか?

解決 3

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

他のヒント

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.

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top