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?

Asked By: Tuomas Toivonen

||

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 package.zip.

Answered By: Stephen Kitt
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)

Answered By: udayakumar

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.

Answered By: Harvastum

You need to use -j or --junk-paths in the command to avoid parent directory and zip only the file.
Zip command reference

-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).

Reference of the answer

Answered By: Yougeshwar Khatri
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.