There are multiple directories under "home" directory. dir1 dir2 dir3 dir4 dir5

I want bash script to recursively archive dir1-2-3 as dir1.zip, dir2.zip & dir3.zip but exclude dir4 and dir5.

Is it doable ?


No, Linux removed that feature with the latest release.

Only joking, of course it's doable.

for dir in dir1 dir2 dir3; do
    zip -r "$dir" "$dir"

If the directories truly have the same prefix:

for dir in dir[1-3]; do
    zip -r "$dir" "$dir"

This assumes that the loop is performed in the correct directory.

If you have many many directories and only want to exclude a few, use bash with its extglob shell option set:

shopt -s extglob
for dir in dir!(4|5); do
   test -d "$dir" || continue
   zip -r "$dir" "$dir"

The pattern dir!(4|5) will match any name starting with dir and then continuing with anything not a 4 or a 5. The pattern could also have been written dir!([4-5]) or !(dir4|dir5).

I've also made sure, in the last loop, that any matched name that is not the name of a directory is skipped.

  • Is it possible to Exclude instead of Include ? There are about 50 directories to archive and 3-4 to exclude.
    – Dhillon
    Sep 14 '17 at 12:58
  • 1
    use for dir in $(ls | grep -Ev '^(dir4|dir5)$'); do ... Sep 14 '17 at 13:03
  • @Dhillon See update.
    – Kusalananda
    Sep 14 '17 at 13:11
  • @MichaelDaffin Does not work for all possible names.
    – Kusalananda
    Sep 14 '17 at 13:11
  • @Kusalananda dir4, dir5 were just example. Could you please post how to exclude if directories are named as "first, second and third". Regards,
    – Dhillon
    Sep 14 '17 at 13:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.