Prepend prefix in tar
Become or hire the top 3% of the developers on Toptal https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Thinking It Over
--
Chapters
00:00 Question
00:28 Accepted answer (Score 37)
01:04 Answer 2 (Score 18)
01:19 Answer 3 (Score 1)
02:25 Answer 4 (Score 0)
02:54 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.