[kwlug-disc] tar --directory help please
Chris Irwin
chris at chrisirwin.ca
Wed Jun 4 14:51:53 EDT 2025
On Wed, Jun 04, 2025 at 10:33:42AM -0700, Ronald Barnes via kwlug-disc wrote:
>
>I've always found the --directory option for `tar` to be so
>frustrating as to be worse than useless.
>
>
>Can someone explain this behaviour?
-C/--directory changes to a specific directory before processing files
aftere it. It's useful in only specific scenarios where you want your
tar to be relative to a specific base directory (or include files from
mutiple directories, but in the same shared path within the tar), and
you know the contents by name. Your file list can't use shell wildcards
(because tar will be working outside of $PWD, bash can't expand them),
and tar doesn't accept wildcards itself (so you can't pass
mail\*.service as your file list).
For example, if you wanted to tar up the files relative to the systemd
directory you specified, you could:
$ tar -cf /tmp/test.tar \
--directory /etc/systemd/system/ \
mailman3.service \
mailman3-web.service
Personally, in this scenario I always found it easier to use pushd/popd
in scripts since you're only including files relative to one directory.
It's less weird, and easier to read. As a bonus, you can use shell
wildcards again.
$ pushd /etc/systemd/system
$ tar -czf /tmp/test.tar mailm*
$ popd
Both of the above provide the same contents:
$ tar -tf /tmp/test.tar
mailman3.service
mailman3-web.service
All that said, it looks like in your example, you're trying to preserve
the full path (hence --directory=/). You don't need to use --directory
for that. Just provide the full path to the files, that will be
preserved in the zip.
$ tar -cf /tmp/test.tar /etc/systemd/system/mailm*
That provides the full path with no --directory required:
$ tar -tf /tmp/test.tar
etc/systemd/system/mailman3.service
etc/systemd/system/mailman3-web.service
I also use filelists (such as your find example in another reply), but
usually for more complex tasks than this (ex: to tar files that match a
grep regex or something else externally driven).
--
Chris Irwin
email: chris at chrisirwin.ca
xmpp: chris at chrisirwin.ca
web: https://chrisirwin.ca
More information about the kwlug-disc
mailing list