docHoliday
docHoliday

Reputation: 291

Output A tar archive into a specific path in a bash script

I have a part in my script that uses tar to archive some folders. It should output the archived result to a specified folder.

The following tar command outputs the file to the right folder but makes the resulted archive nested with the full path leading to it.

e.g. Inside my tar file I have the following folders: full/path/to/file

The folder structure shouldn't look like that it should be relative to the parent folder not the root folder.

Here is the code:

...
local PROJECTS=(~/path/to/folder/*)
...
local PROJECT_PATH="${PROJECTS[$i]}"
local BACKUP_NAME=`date +%d%b%y`.tar.gz
echo Making folder "${PROJECT_PATH}"/backups
tar -czvf $PROJECT_PATH/backups/$BACKUP_NAME $PROJECT_PATH --exclude="${PROJECT_PATH}"/node_modules --exclude="${PROJECT_PATH}"/backups

Upvotes: 1

Views: 3441

Answers (1)

muru
muru

Reputation: 4887

If you want tar to save paths relative to some directory, use -C to change to that directory and provide relative paths:

tar -czvf "$PROJECT_PATH/backups/$BACKUP_NAME" -C "$PROJECT_PATH" . --exclude=./node_modules --exclude=./backups

-C "$PROJECT_PATH" tells tar to change to the $PROJECT_PATH directory, and the following . tells it to archive its current directory.

Upvotes: 2

Related Questions