Problem creating a tar ball in different directories

Hi all. I'm hitting a problem creating a tar archive in one directory from files located in a different directory. It fails when I replace the absolute paths with variables in the script but works if I just run tar on the cmdln. E.g.

#!/bin/ksh

BASE=$PWD
STAGE=$BASE/stage
LOG=$BASE/log
FILENAME=test.tar.gz

$(tar -zcvf $STAGE/${FILENAME} ${LOG}/*)

This gives the following error

tar: Removing leading `/' from member names

I saw some posts about this saying to use -C but that didn't help. Also, tried to change dir in to the log dir and run e.g.

$(cd $LOG && tar -zcvf $STAGE/${FILENAME} *)

but that gives an error, although it appear to actually create the gz file correctly.

 "./a.ksh[11]: a.b: not found [No such file or directory]"

where a.b is the file in the log sub dir that's being tarred.

I don't understand why you have your tar command embedded in a process substitution:

$(tar -zcvf $STAGE/${FILENAME} ${LOG}/*)

This would cause the output of tar (and you have it in verbose mode) being collected into a shell-variable:

tar_log=$(tar -zcvf $STAGE/${FILENAME} ${LOG}/*)

As you are not doing this I can only imagine the output of tar is being interpreted by your shell process.

As for the leading "/" error, tar is attempting to prevent absolute file paths to be entered into the archive so you don't overwrite anything when extracting the archive. I don't know the -C switch but imagine it should be used thus:

tar -zcv -C ${LOG} -f ${STAGE}/${FILENAME} . 

Andrew

1 Like

Good points Andrew. Thanks.

Yeah the 'tar: Removing leading `/' from member names' warning is there for our own benefit so I guess it's simpler to just do everything in 3 steps and get around any issues ...

cd ${LOG} && tar -zcf ${FILENAME} * && cp ${FILENAME} ${STAGE}

How about pax
The compression is not POSIX, but it should work almost everywhere.
Notice you cannot append to compressed archive with pax, if you require such feature.

pax -wzf ${STAGE}/mybackup.tar.gz  ${LOG}

Will create compressed archive from ${LOG} directory (everything in it) into ${STAGE}/mybackup.tar.gz

It also supports to substitute paths inside archive in one go, and a lot more, in one line.
Check it out online or on these forums!

Hope that helps
Regards
Peasant.

No, use the absolute path for the target tarball (as in my example).

Andrew