0
votes

I want to tar a directory (including that directory itself) but I do not want the parent directory and I want to save it in the current working directory.

I am using:

'''cd /home/user/directory'''

'''tar -zcvf backup.tar.gz *'''

but it only saves the files and folders inside of /directory, not /directory itself as the head directory of the tar.

Further, I want the bash script to save the tar file in the current working directory of the user. I'm quite new to bash scripting so any help would be appreciated!

2
I forgot to mention, I thought I was doing the right thing when I used: tar -zcvf backup.tar.gz /home/user/directory before, but then it also saves the /home and /user directories as well, which I don't wantthebaconator
cd ..; tar -zcvf backup.tar.gz directoryWilliam Pursell
cd /home/user/ && tar -zcvf backup.tar.gz directory.Roadowl
cd .... || { echo "Something went wrong!" >&2; exit 1; } ; .... Just in case cd failed for one reason or another you will have an error and the rest of the code/command will not be executed...Jetchisel

2 Answers

0
votes

The * (at the end of your tar command) expands to "everything in the current directory", and all of that will be passed as arguments to your tar command. Try to run

echo *

to see what I mean.

You probably want something like:

cd /home/user
tar zcvf backup.tar.gz directory
0
votes

It is possible to add prefixes (and manipulate filenames, paths) in tar archives by using --transform (from man tar):

--transform=EXPRESSION, --xform=EXPRESSION

use sed replace EXPRESSION to transform file names

You'd like to add a directory, which can be done with the following transform expression:

's,^,directory/,'

, = delimiter, could be basically anything as long as the same characters is used in all places

s = search and replace

^ = beginning of line

directory/ = text of choice

Basically it says, "replace the beginning of the line with directory/".

Example:

→ tree -a .
.
├── dir1
│   └── file3
├── file1
└── file2
→ tar --transform 's,^,directory/,' -zvcf backup.tar.gz *
dir1/
dir1/file3
file1
file2
→ tar tf backup.tar.gz
directory/dir1/
directory/dir1/file3
directory/file1
directory/file2
→ mkdir tmp && cd tmp/
→ tar xf ../backup.tar.gz
→ tree -a .
.
└── directory
    ├── dir1
    │   └── file3
    ├── file1
    └── file2