Create a Tar. Xz in One Command
I Am Trying to Create A. Tar. Xz Compressed Archive in One Command. What Is the Specific Syntax for That? I Have Tried Tar Cf - File | Xz File. Tar. Xz, but...
I am trying to create a .tar.xz compressed archive in one command. What is the specific syntax for that?
I have tried tar cf - file | xz file.tar.xz, but that does not work.
6 Answers
Use the -J compression option for xz. And remember to man tar :)
tar cfJ <archive.tar.xz> <files>
Edit 2015-08-10:
If you're passing the arguments to tar with dashes (ex: tar -cf as opposed to tar cf), then the -f option must come last, since it specifies the filename (thanks to @A-B-B for pointing that out!). In that case, the command looks like:
tar -cJf <archive.tar.xz> <files>
Switch -J only works on newer systems. The universal command is:
To make .tar.xz archive
tar cf - directory/ | xz -z - > directory.tar.xz
Explanation
tar cf - directoryreads directory/ and starts putting it to TAR format. The output of this operation is generated on the standard output.|pipes standard output to the input of another program...... which happens to be
xz -z -. XZ is configured to compress (-z) the archive from standard input (-).You redirect the output from
xzto thetar.xzfile.
If you like the pipe mode, this is the most clean solution:
tar c some-dir | xz > some-dir.tar.xz
It's not necessary to put the f option in order to deal with files and then to use - to specify that the file is the standard input. It's also not necessary to specify the -z option for xz, because it's default.
It works with gzip and bzip2 too:
tar c some-dir | gzip > some-dir.tar.gz
or
tar c some-dir | bzip2 > some-dir.tar.bz2
Decompressing is also quite straightforward:
xzcat tarball.tar.xz | tar x
bzcat tarball.tar.bz2 | tar x
zcat tarball.tar.gz | tar x
If you have only tar archive, you can use cat:
cat archive.tar | tar x
If you need to list the files only, use tar t.
Quick Solution
tarxz() { tar cf - "$1" | xz -4e > "$1".tar.xz ; }
tarxz name_of_directory
(Notice, not name_of_directory/)
Must Read
Using xz compression options
If you want to use compression options for xz, or if you are using tar on MacOS, you probably want to avoid the tar -cJf syntax.
According to man xz, the way to do this is:
tar cf - filename | xz -4e > filename.tar.xz
Because I liked Wojciech Adam Koszek's format, but not information:
ccreates a new archive for the specified files.freads from a directory (best to put this second because-cf!=-fc)-outputs to Standard Output|pipes output to the next commandxz -4ecallsxzwith the-4ecompression option. (equal to-4--extreme)> filename.tar.xzdirects the tarred and compressed file tofilename.tar.xz
where -4e is, use your own compression options.
I often use -k to --keep the original file and -9 for really heavy compression. -z to manually set xz to zip, though it defaults to zipping if not otherwise directed.