Tar with variable date in separate shell

Hi,

I am trying to Zip a folder inside a shell script like below. It successfully taring but it only returns Null inside the variables. Searched a lot but no clue to finding the root cause.

testno=1; 
date=20171128; 
DIR=/root/ sh -c 'cd $DIR; tar cvf "AWS.${testno.${date}.tar" "./AWS"'

please help..

BR
PD

I think that the problem you have is that you have single quoted the whole process. This will prevent the shell from interpolating your variables to build the command it executes. It will literally run what is shown.

Try the following very similar variation:-

DIR=/root/ sh -c "cd $DIR; tar cvf AWS.${testno.${date}.tar ./AWS

You could also try:-

DIR=/root
cd $DIR
tar cvf AWS.${testno.${date}.tar ./AWS

....or if you need to get back to where you started (and that could be anywhere)

DIR=/root
pushd $DIR
tar cvf AWS.${testno.${date}.tar ./AWS
popd

I hope that one of these helps,
Robin

Why do you need a sh command at all?

Thank you all for your kind time and reply .
I ve searched for my requirement and found somthing like below hence tried to modify that command.

#DIR=~/test/ sh -c 'cd $DIR; du -a | cut -d/ -f2 | sort | uniq -c | sort -nr'

But its seems Pushd and Popd is much simpler.I will go with it.

DIR=/root
pushd $DIR
tar cvf AWS.${testno}.${date}.tar ./AWS
popd

Thank you again for all your time.. Love unix.com

1 Like

If you're using a shell that doesn't provide pushd and popd , you can also use:

DIR=/root
if cd "$DIR"
then	tar cvf AWS.${testno}.${date}.tar ./AWS
	cd -
fi

And I tend to use a subshell:

DIR=/root
(cd "${DIR}" && tar cvf AWS.${testno}.${date}.tar ./AWS)

Andrew