Danny Lin
Danny Lin

Reputation: 2300

tar folder/file with a different inner path?

Say I have a folder:

/home/user/blah
/home/user/blah/file1
/home/user/blah/file2
...

I want to compress it into the file /home/user/backup/blah-20131103.tar with the inner structure:

blah-20131103
blah-20131103/file1
blah-20131103/file2
...

How should I write the command?

Upvotes: 0

Views: 412

Answers (2)

petrus4
petrus4

Reputation: 614

As far as I know, this should work. I've made backup tarballs with internal directory trees before.

cd /home/usr/ # To put you one level above "blah."

mv blah blah-20131103

tar jcvf blah-20131103.tar.bz2 blah-20131103 # This command compresses with bzip2.

cd blah-20131103
rm -v file1 file2
cd ..
rmdir blah-20131103 

The reason why I did that rm operation the long way, is because although you can just do

rm -rf blah-20131103

That is very dangerous if you make a typo. If you go into the directory itself, delete the files with neither the recursive or force flags for rm, then cdup and use rmdir to get rid of the file, that is much safer, because you can make sure that the commands only have the power to get rid of the specific files you want. If you make a mistake, it won't hurt you.

I also always use the -v flag (verbose) for rm, to make sure I get a written record of what it does. As mentioned, rm can have catastrophic consequences if you are careless, so you have to be very cautious, and make sure that it only has just the right amount of capability, to do what you want and no more.

An even safer strategy would be to do this:-

mv blah-20131103 /tmp
cd /tmp
rm -rf blah-20131103
cd ~

This way you can use rm with the recursive and force flags to get rid of the whole thing in one hit, but because you've moved the directory to /tmp and done it there, there is no risk of accidentally deleting anything which is potentially important to you.

Upvotes: 0

Kevin
Kevin

Reputation: 56049

It looks like gnu tar has a --transform option you can use:

tar cf ~/backup/blah-20131103.tar --transform='s|^/home/user/blah/|blah-20131103/|' ~/blah

If you don't have gnu tar, make a symlink with the name you want and use the H option.

cd
ln -s blah{,-20131103}
tar cfH backup/blah-20131103.tar blah-20131103
rm blah-20131103

Upvotes: 3

Related Questions