0

I'm creating a tar file using the -P flag, meaning that all paths are absolute (leading / is not stripped from files names). I use it because I'm tarring multiple directories and I need each file to be extracting to its correct location.

I'm using a script to extract the tar file, and I need an ability to extract the files to another directory if an optional argument is provided.

I create the tar file like this:

tar pcjfPv "${ARCHIVE_NAME}".tmp.bz  ${DIR_A} ${DIR_B}

${DIR_A} is /path/a and ${DIR_B} is /path/b.

If I execute the extracting script with no argument I expect the files to go to their correct directories. This part works as expected with tar mxfvjpP.

However when the script recies a path in the argument I want to extract the files to /path/from/argument/path/a and /path/from/argument/path/b.

Is this even possible? This is what I currently have:

if [ ! -d "${EXTRACT_TO}" ]; then
    echo "${EXTRACT_TO} does not exist, creating."
    mkdir -p ${EXTRACT_TO}
fi
tar mxfvjP - -C ${EXTRACT_TO}

That does not work. The path in ${EXTRACT_TO} is created, but the files are still extracted to /path/a and /path/b.

NOTE: I can't modify the tar file.

2
  • 1
    Don't create tar with -P and extract with -C /.
    – Cyrus
    Aug 22, 2019 at 9:11
  • @Cyrus Thanks, that exactly what I ended up doing
    – DeepSpace
    Aug 22, 2019 at 10:18

1 Answer 1

2

In my Debian extracting without -P yields Removing leading '/' from member names. Maybe all you need is not to use -P while extracting to another directory.


If there's any problem with the above approach, consider --transform. From man 1 tar:

--transform=EXPRESSION, --xform=EXPRESSION
Use sed replace EXPRESSION to transform file names.

So this

tar -x --transform='s|^/||' …

will remove one leading slash (if it's there) from each path. But because ////foo is equivalent to /foo, the following seems better:

tar -x --transform='s|^/*||' …

It will remove all leading slashes.

1
  • Thanks, I ended up compressing without -P and using -C / and -C ${EXTRACT_TO}
    – DeepSpace
    Aug 22, 2019 at 10:19

You must log in to answer this question.

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