Is it possible to create a target directory, similar to mkdir -p, where I can define a non-existent target directory within my tar command, and tar will create the directory for me?

I know I can redirect the output to a directory using tar -C /target/dir, but this doesn't work if the target directory is non-existent.

  • 3
    If it isn't possible, you could always create a shell alias. – n0pe Nov 25 '11 at 4:02
mkdir -p /target/dir && tar -C /target/dir
  • 3
    No spoonfeeding, straight and to the point. – Amado Martinez Oct 31 '16 at 6:56
  • 9
    Minor suggested change: mkdir -p /target/dir && tar -C $_ – Mark Melville Jan 13 '17 at 22:41
  • @MarkMelville describe to us what $_ supposed to de here – Suhayb Apr 22 at 20:13
  • @Suhayb $_ is a special parameter in Bash that expands to the last argument to the previous command. – ConceptRat May 28 at 4:09
tar -xvf bash.html_node.tar.gz --one-top-level

From man page of tar command


    Extract all files into DIR, or, if used without argument, into a subdirectory named by the base name of the archive (minus standard compression suffixes recognizable by --auto-compress).

----- test

test 1

tar zxvf ../aaa.tgz --one-top-level

tree aaa
├── 111
└── 222

// if tgz name same as root_dir of archive, no other effect

test 2

mv ../aaa.tgz ../bbb.tgz

tar zxvf ../bbb.tgz --one-top-level

tree bbb
└── aaa
    ├── 111
    └── 222

// if tgz name not same as root_dir of archive, create a top-level dir

  • Requires GNU tar? Mac default bsd tar does not have this option. – Curtis Yallop Apr 18 at 18:12

This made more sense to me: mkdir -p /create/folder && tar -zxf haroopad-v0.13.0_x64.tar.gz -C /create/testfolder

mkdir makes the folder although I don't quite understand the -p switch. && lets you execute a second command. I used typical tar switches but at the end -C is used to change directories and extract to that location needed.

reference: extract-files-contained-in-archive-tar-gz-to-new-directory-named-archive

  • 2
    The -p switch will not throw an error if the directory already exists. – David Sep 3 '15 at 21:10
  • @David it will also create any leading non-existing directories, i.e. it'll create /create if it doesn't exist. – Antonio Pérez Oct 21 '15 at 13:40

If you don't know the paths to create...
Get the needed paths from the tar file, then create them...

for P in \`tar tvf tarfile.tar |tr -s [:space:] |cut -d' ' -f6\`; do  
    C=\`echo "${P: -1}"\`  #get the last character  
    if [ $C = '/' ]; then  
        echo "Found directory: $P"  
        mkdir -p $P  

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.