At linux instance, I have a directory named test under the location /var/lib/work_directories/ which needs to be zipped at /home/test_user/ location as test.zip.
I am able to create a zip-file from location /home/test_user/ using the below command:
zip test.zip /var/lib/work_directories/test
But when I unzipped it using the below command, I can see it had zipped var and I need to navigate all towards the end:
unzip test.zip
So, after unzipping test.zip, it looks like /home/test_user/var/lib/work_directories/test/ but I ideally I expect something like this /home/test_user/test/<:contents:>
Any suggestions would be really helpful! Thanks in advance!
Your approach will depend on the structure of /var/lib/work_directories/test
. If the directory is flat without any sub directories you can simply use the -j
flag which will strip all parent directories (including the immediate parent test/
):
$> tree test
test
├── a
├── b
└── c
$> zip -rj test.zip test
updating: a (stored 0%)
updating: c (stored 0%)
updating: b (stored 0%)
As you can see, all but the basename for each file is stripped from the stored value.This will likely not serve you well in most cases. The simplest solution is to just cd
to the target directory and zip. Something like cd /var/lib/work_directories && zip -r test.zip test
As a script this would like something like this:
# absolute path to target directory
absolute=/var/lib/work_directories/test
# parent directory
dir="$(dirname $target)"
# directoy basename
base="$(basename absolute)"
cd "$dir"
zip -r "$target.zip" "$target"
This would result in only the last directory name being included:
updating: test/ (stored 0%)
adding: test/a (stored 0%)
adding: test/c (stored 0%)
adding: test/b (stored 0%)
If you must return to the same location in the directory tree after the zip as before you can leverage push
and popd
for a similar effect:
# absolute path to target directory
absolute=/var/lib/work_directories/test
# parent directory
dir="$(dirname $target)"
# directoy basename
base="$(basename absolute)"
pushd "$dir"
zip -r "$target.zip" "$target"
popd