Does tar have any option where, when creating an archive, if the target directory does not exist, it creates it on it's own?

So I got folders /1/2 but I don't have folder /1/2/3/. Is there any option I could use for tar to be able to make it?

I need it for a script, but if there is no option, would it just be better to do something like this?

mkdir /1/2/3/ &> /dev/null

If the folder isn't there, it's gonna get created, but if it already is there, I won't get an error massage because I shoved all of it into null.

Now with this method, is there ANYTHING that could go wrong?

Basically, I'm making a script that deletes users, but you can choose an option to archive their home directories before the script deletes the user. In order to make the script usable on other machines, I have to create a folder called /archives, which may or may not exist on other machines.

Since tar apparently cannot recursively create whatever path you specify for the archive (for example it cannot create /archives/users if you write tar -czf /archives/users/user1.tgz /home/user1/ if /archives does not exist.

Which lead me to my question about my solution: writing mkdir -p /archives/users/ &> /dev/null. Would this mess up anything? Keep in mind that this script can only be run with sudo, since it's a user deletion script.

  • If are do not interested in extract mode, you would need to explain your question or it is not possible to give you an answer.
    – schily
    Aug 23 '18 at 12:30

Tar can only combine data which is actually there.

I think a smoother method would be if you check beforehand if the directory exists. The problem with your method is, if the directory can't be created, you won't see an error message.

Here is an example of a test:

test ! -d /1/2/3 && mkdir /1/2/3
  • Thanks, I'll try the test, but if my script runs the mkdir as sudo, would there still be a problem? It's a user deletion script, so you need to be root or use sudo to use it in the first place.
    – iamAguest
    Aug 23 '18 at 12:36
  • You need to give us more information about file permissions so we can answer this question. Which user owns the data? Who can access the data?
    – Tim
    Aug 23 '18 at 12:43

The default behavior of tar is to create missing directories while extracting archives.

If you did use cpio instead of tar, this was different and you would need to give cpio the option -d to tell it to create missing directories.

If you are in create mode, there is no problem that could match your question as it makes no sense to archive non-existing directories.

  • Sorry I forgot to add, it's when I create an archive, not when I extract it.
    – iamAguest
    Aug 23 '18 at 12:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.