7

What is the correct way to use the --remove-files option when using tar?

Is it...

tar -cfvj --remove-files archive.tar.bz2 archive/

Or...

tar -cfvj archive.tar.bz2 archive/ --remove-files
chattsm
  • 329
  • 2
  • 3
  • 7

2 Answers2

13

Since the -f argument is telling tar you are going to speficy the file name of the archive you are acting on, I would keep the archive name right after that argument. The list of files and directories to include in the archive should come last. You can specify --remove-files before your other arguments like this:

tar --remove-files -cvfj archive.tar.bz2 archive/
Caleb
  • 11,813
  • 4
  • 36
  • 49
  • problem with this option for me is that then I no longer get tab completion working on the files part – iss42 Sep 23 '16 at 11:37
  • 1
    @iss42 That is a function of your shell's autocompletion patterns not being as smart as they should be, not of incorrect tar usage. You can fix that problem separately. – Caleb Sep 23 '16 at 12:06
  • @Caleb interesting! Think the one I was using in this case was default Ubuntu setup, can you point me to more info on this? – iss42 Sep 24 '16 at 13:17
  • 1
    @iss42 The thing to do is ask a question about how to fix that completion on [unix.se] and link back to it here. – Caleb Sep 24 '16 at 13:38
  • Shouldn't `-cvfj` be `-cvjf` i.e. the `f` flag just before the filename? – Petr Vepřek Mar 22 '23 at 10:47
1

For me, the archive file name MUST be after the -f option to avoid bad interpretation and make it easier to understand.

In my scripts, I prefer to use this syntax :

tar -cvjf archive.tar.bz2 --remove-files archive/

I've only switched the j and f options and moved the remove before the dir to archive.
The -c (--create) is a function to create the tar file, and must be at the beginning.

guntbert
  • 631
  • 9
  • 21
Pct Mtnxt
  • 11
  • 1