4

When I tar a single file, I can give the tar file a desired name:

$ tar -cvfj A B

I would like to do the same when I untar a single file.

$ tar -xvjf A tmp

(ie. extract A into tmp).

I was trying to do this using mv:

$ tar -xvjf $1 | mv $1 tmp

That didn't work. $1 can be an arbitrary name, but the tar files will always be a single file, no folders (this is guaranteed).

4
  • Are you just using tar for compression? If so, don't do that; just use the compression program directly (bzip2 in your case)
    – Fox
    Sep 2, 2018 at 20:27
  • @Fox yes, I am. What difference does it make?
    – lee
    Sep 2, 2018 at 20:28
  • 3
    If your local tar implementation does not create a file named j in your first example, it is broken.
    – schily
    Sep 2, 2018 at 20:31
  • 1
    Use -C : tar -xvjf $1 -C tmp
    – GAD3R
    Sep 2, 2018 at 20:43

2 Answers 2

7

Since you seem to be using tar with bzip2 compression as a way of just compressing a single file, you may want to consider using bzip2 directly:

To compress a file (creates filename.bz2, deletes filename):

bzip2 filename

To decompress a file (creates filename, deletes filename.bz2):

bunzip2 filename.bz2

To compress to a specific filename (creates newfilename.bz2, keeps filename):

bzip2 -c filename >newfilename.bz2

To decompress to a specific filename (creates newfilename, keeps filename.bz2):

bunzip2 -c filename.bz2 >newfilename

See also the manual for bzip2 on your system (man bzip2).

4
  • I like this solution. However, there is a file that has spaces. How can my bash script handle this? ./decomp "blah blah blah.bz2" gets all messed up. When I used bunzip2 directly, it's all good.
    – lee
    Sep 2, 2018 at 21:47
  • 1
    @SpentDeath Make sure that you double quote the variable expansion in your script.
    – Kusalananda
    Sep 2, 2018 at 21:52
  • what does that mean?
    – lee
    Sep 2, 2018 at 21:59
  • 1
    @SpentDeath That means that rather than $1, you'd use "$1" so that your arguments don't get split
    – Fox
    Sep 3, 2018 at 0:22
7

Here is one solution:

tar -xjOf my.tar > out

This uses the -O option of tar

-O, --to-stdout: extract files to standard output

and redirects standard output to a file called out. If the archive has more than one file, out will be all of the files in the archive concatenated.

You should probably just be using bzip2 directly, as during compression it will not store a file tree. Instead, it will simply store the data within the file.

1
  • 3
    Caveat of this approach is you do not preserve metadata like permissions and symlinks.
    – Bob
    Sep 3, 2018 at 5:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .