Search code examples
bashcopyglobcp

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.


Solution

  • 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