how to prevent overwrite existing files when using tar command

10,494

From man tar:

-k, --keep-old-files
       don’t replace existing files when extracting, treat them as errors

--skip-old-files
       don’t replace existing files when extracting, silently skip over them
Share:
10,494
Rohan Kishibe
Author by

Rohan Kishibe

Apprentice software developer

Updated on June 28, 2022

Comments

  • Rohan Kishibe
    Rohan Kishibe almost 2 years

    I made a mistake that forgot to assign argument of the file name when using tar command like below:

    [john@foobar foo]$ ll
    total 0
    -rw-rw-r-- 1 john john 0  7月  4 19:20 2018 file1
    -rw-rw-r-- 1 john john 0  7月  4 19:20 2018 file2
    -rw-rw-r-- 1 john john 0  7月  4 19:20 2018 file3
    [john@foobar foo]$ tar -cvzf file1 file2 file3
    file2
    file3
    [john@foobar foo]$ ll
    total 4
    -rw-rw-r-- 1 john john 130  7月  4 19:21 2018 file1
    -rw-rw-r-- 1 john john   0  7月  4 19:20 2018 file2
    -rw-rw-r-- 1 john john   0  7月  4 19:20 2018 file3
    

    When forget to assign archive file name, tar overwrites and creates the archive file1.

    I checked man tar, but it seems there is no option such as cp shows a prompt when same name file already exists.

    To create a foolproof script is a possible way?

  • Rohan Kishibe
    Rohan Kishibe almost 6 years
    This option is for extracting. when creating an archive, this option doesn't work.
  • Poshi
    Poshi almost 6 years
    Ouch! Sorry, I understood you were talking about extracting files. In that case, you should check beforehand: stackoverflow.com/questions/21680601/…