Reputation: 601
How to tar only a file present in the directory. I have tried tar -cvf /tmp/test.tar /tmp/mylog.doc
being in home diretory,but when I untar it the contents included tmp
directory too. I need only the file mylog.doc
to be present in the tar file. I see the similar query
Tarring only the files of a directory. but could not get much help from it.
Upvotes: 0
Views: 6225
Reputation: 3791
cd sourcedir ; tar cvf archive.tar ./file_to_tar
because using "/path/to/file" or "./path/to/file" : will add "path/to/" in the resulting tar file (unless specific (and also probably non-portable) options telling tar otherwise)
note: some not-so-old production system also still can't get rid of the leading "/" when extracting.
On those 'not-so-old' systems:
tar cvf /tmp/hosts-backup.tar /etc/hosts
cd /secure/location
tar xvf /tmp/hosts-backup.tar
will overwrite the file /etc/hosts, instead of outputing a "./etc/hosts" file underneath /secure/location ! (as most 'recent' tar now do : they now all silently ignore the trailing "/", making the path relative instead of absolute, which is what 99.9% of people want)
I've been burned recently with this : wanted to extract a log, and that log ended up overwriting the original location (and thus overwrote the more recent log file there). Always check for this before using tar for the first time on a system. (there are a few workarounds, but not too simple : chroot, and other commands such as "sar")
Upvotes: 0
Reputation: 37427
Use -C
command line parameter to indicate the directory you wanna work in. Then, you can use the filename you include relative to this directory.
tar -cvf /tmp/test.tar -C /tmp mylog.doc
Note that this does not apply to the tar file itself.
Upvotes: 4