19

I have a folder that contains multiple files

folder

  • artifact1.app
  • artifact2.ext2
  • artifact3.ext3
  • ...

My goal is to zip the file from outside this folder (so without using cd command) without including the folder dir.

zip -r ./folder/artifact.zip ./folder/artifact1.app

This command includes the folder dir in the final zip. Any hints?

Related question: Zip the contents of a folder without including the folder itself

Lorenzo B
  • 439
  • 1
    From the man pages, it seems like only -j would apply, and that'd compress all folders into a single root-level directory within the ZIP. That's not what you're looking for, is it? – phyrfox Nov 27 '15 at 11:02
  • @phyrfox Maybe yes. Need to verify it. Thanks. – Lorenzo B Nov 27 '15 at 11:03

1 Answers1

22

If you want to store all the files in folder under their name without a directory indication, you can use the -j option.

zip -j folder/artifact.zip folder/artifact1.app folder/artifact2.ext2 folder/artifact3.ext3

or

zip -j folder/{artifact.zip,artifact1.app,artifact2.ext2,artifact3.ext3}

If you have files in subdirectories, they won't have any directory component in the archive either, e.g. folder/subdir/foo will be stored in the archive as foo.

But it would probably be easier to change to the directory. It's almost exactly the same amount of typing as the brace method aboe. If you do that, if you include files in subdirectories, they'll have their relative path from the directory you changed into, e.g. folder/subdir/foo will be stored as subdir/foo.

(cd folder && zip artifact.zip artifact1.app artifact2.ext2 artifact3.ext3)

For interactive use, you lose shell completion this way, because the shell doesn't realize that you'll be in a different directory when you run the zip command. To remedy that, issue the cd command separately. To easily go back to the previous directory, you can use pushd and popd.

pushd folder
zip artifact.zip artifact1.app artifact2.ext2 artifact3.ext3
popd

If you want full control over the paths stored in a zip file, you can create a forest of symbolic links. Unless instructed otherwise, zip doesn't store symbolic links.

  • You don't have to explicitly list all the files in the the subdirectory (folder), you can just use a wildcard, i.e. zip -j folder/* – Jakub Kukul Jan 24 '18 at 17:04
  • Relying on shell expansion means that dotfiles (e.g. .profile) won't be included in the archive. Instead, change the current working directory and specify . as the file to be archived: cd folder && zip -r ../folder.zip . – sheldonh Feb 07 '18 at 08:49