How can I automatically remove files after they've been archived?

8

1

How do i archive and remove excess files example.

cd ~/Desktop && tar -cvf sitepack.tar ./

this will give me

ls
Riva_Starr_Feat._Noze_I_Was_Drunk_Official_Video_HD_.mp3
Riva_Starr_feat._Sud_Sound_System_Orizzonti_Official_Vide.mp3
Riva_starr_I_was_drunk_Syskey_remix_.mp3
sitepack.tar

when what i am looking for is

ls
sitepack.tar

so it archive everything into the zip rather than leave them in place?

user1503606

Posted 2012-10-18T10:10:12.250

Reputation: 285

Answers

13

If you're using GNU tar, you can use the --remove-files option:

--remove-files

remove files after adding them to the archive

That's not portable though.

If your tar doesn't have that, you'll need to do it manually, in two steps.
I'd suggest you don't put the tar file in the directory you're packing up, but put it in the parent directory. That way you can simply rm * (possibly recursively) after tar is done.

Mat

Posted 2012-10-18T10:10:12.250

Reputation: 6 193

Full mwe: tar tf /file.tar --remove-files – Justapigeon – 2020-01-04T18:48:14.820

2There's always tar cvf <out-file> <in-files> | xargs rm -f as well to remove files immediately after adding them if your tar doesn't support the above GNU extension. – Mark K Cowan – 2013-10-20T12:46:01.863

1

[max@localhost zzz]$ touch 1 2 3 4
[max@localhost zzz]$ ll
total 0
-rw-rw-r-- 1 max max 0 Oct 18 16:13 1
-rw-rw-r-- 1 max max 0 Oct 18 16:13 2
-rw-rw-r-- 1 max max 0 Oct 18 16:13 3
-rw-rw-r-- 1 max max 0 Oct 18 16:13 4

To create a archive use this command

-c ---------> For Create a archeive

[max@localhost zzz]$ tar -cvf max.tar 1 2 3 4
1
2
3
4
[max@localhost zzz]$ ls -l max.tar 
-rw-rw-r-- 1 max max 10240 Oct 18 16:14 max.tar

To list a content of archive use this command

-t ---------> List all files in archive

 
[max@localhost zzz]$ tar -tvf max.tar
-rw-rw-r-- max/max           0 2012-10-18 16:13 1
-rw-rw-r-- max/max           0 2012-10-18 16:13 2
-rw-rw-r-- max/max           0 2012-10-18 16:13 3
-rw-rw-r-- max/max           0 2012-10-18 16:13 4

To extract use this command

-x ---------> To extract from archive

-v ---------> For verbose mode

[max@localhost zzz]$ tar -xvf max.tar -C direc1
1
2
3
4

Here -C extract the content to directory direc1

To extract a single file from archieve use this command

[max@localhost zzz]$ tar -xvf max.tar 1 -C direc1
1

Give the file name you want to archive in my case file name is `1`

[max@localhost zzz]$ tar -cvf max.tar 1 2 3 4 --remove-files

This will remove original files after achieving

max

Posted 2012-10-18T10:10:12.250

Reputation: 3 329

Why the dash in "tar -cvf"? That's never worked for me in gnu tar. – RonJohn – 2018-03-02T15:46:23.190