This question already has an answer here:

I am using this for d in ./*/ ; do (cd "$d" && cp -R ../lib . ); done in a shell script to copy lib folder in all subfolder inside my parent directory . But the lib folder also getting copied inside lib . How to avoid that ?

marked as duplicate by PSkocik, Anthon, Rahul, Networker, heemayl Aug 11 '16 at 13:51

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


Without extglob:

for d in */ ; do
    if [ "$d" != "lib/" ]; then
        cp -R lib "$d"

Or just delete it afterwards... (well, unless lib/lib exists beforehand!)

for d in */; do cp -R lib "$d"; done
rm -r lib/lib

(Somewhat amusingly, GNU cp says cp: cannot copy a directory, 'lib', into itself, 'lib/lib', but does it anyway.)


One way:

shopt -s extglob
for d in ./!(lib)/; do #...

Or maybe move it out so it doesn't match:

mv lib ../ #better not have a conflicting ../lib directory there
for d in */; do cp -R ../lib "$d"; done

Using the does-not-include option of ls command:

for d in $(ls -I lib -1 */) ; do cp -R lib "$d" ; done
  • That ls will list all the files in the subdirectories (it's what it does when given a directory on the command line), and it won't ignore lib because it's given on the command line, through the glob (try ls -l -I lib lib). And parsing ls like that will burn if you have filenames with spaces. – ilkkachu Aug 11 '16 at 13:29
  • you could get close with ls -I lib . or ls -d -I lib */, but you get either regular files too (which */ doesn't give), or lib/ too (since it's in the glob). – ilkkachu Aug 11 '16 at 13:31
  • You're right but I have expected that there are only directories in the current path. – zentoo Aug 12 '16 at 15:15

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