I need to create a zip file using this command:
zip /dir/to/file/newZip /data/to/zip/data.txt
This works, but the created zip file creates
You can use -j
.
-j
--junk-paths
Store just the name of a saved file (junk the path), and do not
store directory names. By default, zip will store the full path
(relative to the current directory).
unzip
doesn't spew files everywhereWhen zipping directories, keeping the parent directory in the archive will help to avoid littering your current directory when you later unzip the archive file
So to avoid retaining all paths, and since you can't use -j and -r together ( you'll get an error ), you can do this instead:
cd path/to/parent/dir/;
zip -r ../my.zip ../$(basename $PWD)
cd -;
The ../$(basename $PWD)
is the magic that retains the parent directory.
So now unzip my.zip
will give a folder containing all your files:
parent-directory
├── file1
├── file2
├── dir1
│ ├── file3
│ ├── file4
Instead of littering the current directory with the unzipped files:
file1
file2
dir1
├── file3
├── file4
Use the -j
option:
-j Store just the name of a saved file (junk the path), and do not
store directory names. By default, zip will store the full path
(relative to the current path).
Alternatively, you could create a temporary symbolic link to your file:
ln -s /data/to/zip/data.txt data.txt
zip /dir/to/file/newZip !$
rm !$
This works also for a directory.
Using -j
won't work along with the -r
option.
So the work-around for it can be this:
cd path/to/parent/dir/;
zip -r complete/path/to/name.zip ./* ;
cd -;
Or in-line version
cd path/to/parent/dir/ && zip -r complete/path/to/name.zip ./* && cd -
you can direct the output to /dev/null
if you don't want the cd -
output to appear on screen
Somewhat related - I was looking for a solution to do the same for directories.
Unfortunately the -j
option does not work for this :(
Here is a good solution on how to get it done: https://superuser.com/questions/119649/avoid-unwanted-path-in-zip-file