zip all files and subfolder in directory without parent directory
I have the following folder structure
folder | |--foo.txt | |--sub_folder | |--bar.txt
I want to zip the content (files and sub folders) of folder without including the root folder in the zip.
I have tried command
zip -r package.zip folder
But this includes the root folder. Also tried the following form
zip -j -r package.zip folder
But this will flatten all the directory structures and just include the files. How do I preserve the internal directory structure but ignore the parent folder?
zip stores paths relative to the current directory (when it is invoked), so you need to change that:
(cd folder && zip -r "$OLDPWD/package.zip" .)
&& ensures that
zip only runs if the directory was correctly changed, and the parentheses run everything in a subshell, so the current directory is restored at the end. Using
OLDPWD avoids having to calculate the relative path to
zip -r package.zip folder/*
The above command will zip all files and sub folders under
folder directory (It will ignore the parent directory for folder)
To add to other answers, for scripts, you could use
pushd folder; zip -r ../package.zip .; popd
pushd changes the directory much like
cd, but remembers the previous one, and
popd restores the last remembered directory.
In this case it’s equivalent to removing the parentheses (which spawn a new shell) and adding
; cd .. at the end of the command suggested by Stephen.
Note: I would add this as a comment, but I can’t because I do not have enough reputation.
You need to use
--junk-paths in the command to avoid parent directory and zip only the file.
Zip command reference
Store just the name of a saved file (junk the path), and do not store directory
names. By default,
zipwill store the full path (relative to the current