Override an existing folder with cp

10,324

This is what you are looking for

cp -TRv A A.bak

When you use the option -T it overwrites the contents, treating the destination like a normal file and not directory.

from man cp :

-T, --no-target-directory
    treat DEST as a normal file

-v, --verbose
          explain what is being done

Alternatively, you copy the directory's contents and not the directory, like so:

cp -TR A/* A.bak
Share:
10,324

Related videos on Youtube

user179723
Author by

user179723

Updated on September 18, 2022

Comments

  • user179723
    user179723 almost 2 years

    Is it possible to override an existing folder with cp? Example:

    tux@linux:~ $ cd /tmp/test/
    tux@linux:/tmp/test $ mkdir A
    tux@linux:/tmp/test $ cd A
    tux@linux:/tmp/test/A $ touch 1 2 3 4
    tux@linux:/tmp/test/A $ cd ..
    tux@linux:/tmp/test $ cp -R A A.bak
    tux@linux:/tmp/test $ tree
    .
    ├── A
    │   ├── 1
    │   ├── 2
    │   ├── 3
    │   └── 4
    └── A.bak
        ├── 1
        ├── 2
        ├── 3
        └── 4
    
    2 directories, 8 files
    tux@linux:/tmp/test $ touch A/5
    tux@linux:/tmp/test $ tree
    .
    ├── A
    │   ├── 1
    │   ├── 2
    │   ├── 3
    │   ├── 4
    │   └── 5
    └── A.bak
        ├── 1
        ├── 2
        ├── 3
        └── 4
    
    2 directories, 9 files
    tux@linux:/tmp/test $ cp -R A A.bak
    tux@linux:/tmp/test $ tree
    .
    ├── A
    │   ├── 1
    │   ├── 2
    │   ├── 3
    │   ├── 4
    │   └── 5
    └── A.bak
        ├── 1
        ├── 2
        ├── 3
        ├── 4
        └── A
            ├── 1
            ├── 2
            ├── 3
            ├── 4
            └── 5
    
    3 directories, 14 files
    

    But it should be:

    .
    ├── A
    │   ├── 1
    │   ├── 2
    │   ├── 3
    │   ├── 4
    │   └── 5
    └── A.bak
        ├── 1
        ├── 2
        ├── 3
        ├── 4
        └── 5
    
    2 directories, 10 files
    
  • user179723
    user179723 almost 8 years
    I have tried cp -R A -t A.bak, but it didn't work. What does -t mean?
  • Rahul
    Rahul almost 8 years
    what do you mean by didn't work ? I tried same setup on machine, it worked as you were expecting.
  • terdon
    terdon almost 8 years
    @user179723 t is not the same as T.
  • Rahul
    Rahul almost 8 years
    @user179723 do man cp. you will come to know the difference between -t and -T.