I'd use the solution in Rinzwind's answer. There's no real reason to avoid the cd
; especially if you put this in a shell script, as the cd
will affect just the script, not the shell you call the script from.
If you really really don't wan't to use cd
, you can use tar
s --transform
option:
gbl@roran:~$ tar -cf /tmp/archive.tar /home/gbl/Temp/a.out
gbl@roran:~$ tar -tf /tmp/archive.tar
home/gbl/Temp/a.out
gbl@roran:~$ tar --transform 's/^home\/gbl//' -cf /tmp/archive2.tar /home/gbl/Temp/a.out
gbl@roran:~$ tar -tf /tmp/archive2.tar
/Temp/a.out
gbl@roran:~$ tar --transform 's/^home\/gbl\///' -cf /tmp/archive3.tar /home/gbl/Temp/a.out
gbl@roran:~$ tar -tf /tmp/archive3.tar
Temp/a.out
I omitted some tar: Removing leading '/' from member names
messages here as they don't contribute to the answer.
Use any sed
regular expression for the transformation, read the manual for a few more options.
There's also --strip-components
to remove that many path components from the start of the file name, but it works on extraction only, not when you create an archive.
However, this is restricted to gnu tar, so you'll be ok on Linux, but probably not whenever you switch to MacOS, Solaris, or AIX. Which is another reason to avoid it, especially as there's an easy different solution (cd
first).