0

I have a list of directories. Some of the directories require them to be tared up recursively, other require only the file that exist in that directory, no subdirectories: Using the directory/files below as an example, how would my tar command look:

/tmp/dir1/ - Recursively
/tmp/dir2/ - Only the files that exist in that directory, no subdirectories
/tmp/dir3/file1 - Only this single file.
0

1 Answer 1

1

Here's what I came up with:

First, the directory structure I'm using as an example:

$ find dir1 dir2 dir3 -print
dir1
dir1/file1
dir1/file2
dir1/sub_dir1
dir1/sub_dir1/file1
dir2
dir2/file1
dir2/file2
dir2/sub_dir1
dir2/sub_dir1/file1
dir3
dir3/file1
$

Next, my solution which consists of three commands:

First command:

tar cvf archive.tar dir1

Pretty standard. Let's break it up:

  • c - Create
  • v - Verbose (let's see what's going on)
  • f - the filename we want, in our case archive.tar
  • archive.tar - that actual argument to our f switch
  • dir1 - what we want to actually tar up

Second command:

find dir2 -maxdepth 1 -type f -print0 | xargs -0 tar rvf archive.tar

Let's break it up:

  • find dir2 - Where we want find to search.
  • -maxdepth 1 - Don't go any further down than a depth of 1 (stay at the root of dir2)
  • -type f - Search for files
  • -print0 - Don't print out a newline character at the end, instead use null character. This helps us out if find finds files with whitspace in them.
  • | xargs -0 - The standard input we found with the find command gets thrown here to be executed while respecting our print0
  • tar rvf - The only new switch here is r. This is our append option. It adds to our archive.tar at the end of it. Not to be confused with the A option which is specific to appending additional archives (.tar-s).
  • archive.tar - The tar we want to append to.

    The end of this command is where our stdinput gets used. e.g. archive.tar <stdinput>

Third command:

tar rvf archive.tar dir3/file1

Append to archive.tar a single file (file1) from dir3.

And finally, what the tar looks like after it's created. The t option is used to print out it's contents.

$ tar tvf archive.tar
drwxrwxr-x mmallard/mmallard 0 2019-07-18 16:02 dir1/
-rw-rw-r-- mmallard/mmallard 0 2019-07-18 16:01 dir1/file1
-rw-rw-r-- mmallard/mmallard 0 2019-07-18 16:01 dir1/file2
drwxrwxr-x mmallard/mmallard 0 2019-07-18 16:02 dir1/sub_dir1/
-rw-rw-r-- mmallard/mmallard 0 2019-07-18 16:02 dir1/sub_dir1/file1
-rw-rw-r-- mmallard/mmallard 0 2019-07-18 16:02 dir2/file1
-rw-rw-r-- mmallard/mmallard 0 2019-07-18 16:02 dir2/file2
-rw-rw-r-- mmallard/mmallard 0 2019-07-18 16:02 dir3/file1
$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .