Assuming that bazdir
does not already exist in the current directory, the most straight-forward method that comes to mind is:
$ ln -s . bazdir
$ tar cvf myfile.tar bazdir/{foo,bar}
a bazdir/foo
a bazdir/bar
Once the .tar
file is created, we remove the bazdir
symlink:
$ rm bazdir
The .tar
file now contains the directory prefix bazdir/
:
$ tar tvf myfile.tar
-rw------- 0 jim wheel 0 Dec 11 13:41 bazdir/foo
-rw------- 0 jim wheel 0 Dec 11 13:41 bazdir/bar
And when we extract the tar file, bazdir
gets created as a true directory:
$ tar xvf myfile.tar
x bazdir/foo
x bazdir/bar
$ find .
.
./myfile.tar
./foo
./bazdir
./bazdir/bar
./bazdir/foo
./bar
$ file bazdir
bazdir: directory
If you prefer not to touch the source directory (or indeed if it's read-only), then place the symlink elsewhere:
$ ln -s $(pwd) /tmp/bazdir
$ tar cvf /tmp/myfile.tar -C /tmp bazdir/{foo,bar}
a bazdir/foo
a bazdir/bar
$ rm /tmp/bazdir
$ tar tvf /tmp/myfile.tar
-rw------- 0 jim wheel 0 Dec 11 13:41 bazdir/foo
-rw------- 0 jim wheel 0 Dec 11 13:41 bazdir/bar
tar xf archive.tar
'ed.