Prepend prefix in tar
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping
--
Chapters
00:00 Prepend Prefix In Tar
00:21 Accepted Answer Score 38
00:52 Answer 2 Score 18
01:06 Answer 3 Score 1
01:58 Answer 4 Score 0
02:16 Thank you
--
Full question
https://superuser.com/questions/595510/p...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#bash #tar
#avk47
ACCEPTED ANSWER
Score 38
The GNU version of tar
supports the --transform
option (and its alias --xform
), you could use it like this
tar --transform "s/^$MYPATH/$VERSION/" -cf archive.tar.bz2 "$MYPATH"
For example, given this directory tree
foo
└── foo.txt
the command
tar --transform "s/^foo/bar/" -cf foo.tar.bz2 foo
will produce an archive like
$ tar -tf foo.tar.bz2
bar/
bar/foo.txt
ANSWER 2
Score 18
To tar the current directory and add a prefix, this worked for me:
tar --transform 's,^\.,$VERSION,' -cf foo.tar .
ANSWER 3
Score 1
To add a directory prefix comfortably, use a different separator than /
in the --transform
argument, e.g. +
or ,
like in Andy's answer.
So, for a simpler case, you have a bunch of files in current directory, and you don't want to create a tarbomb.
tar czf logs_nightly.tar.gz --tranform 's+^+logs_nightly/+' *.log
The syntax is s+search+replace+
, and for ^
it simply matches the start of filename.
And now, just to answer the OP - well, you can avoid copying your whole directory to /tmp
by running:
mv $MYPATH $VERSION
tar cjf archive.tar.bz2 $VERSION
mv $VERSION $MYPATH
Alternatively:
ln $MYPATH $VERSION
tar cjf archive.tar.bz2 $VERSION
(hard link, avoids problems with symlinks)
The last two were included for entertainment value, I myself would stick to toro2k's answer.
ANSWER 4
Score 0
If you can get away without preserving symbolic links within the file tree you're tarring, you could do
ln -s $MYPATH /tmp/$VERSION
cd /tmp
tar cjhf archive.tar.bz2 $VERSION
The h
option means dereference symlinks, i.e. include the file or directory that the link points to rather than simply recording the fact that there was a symlink and what it pointed to.