3

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 ?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

3 Answers3

3

Without extglob:

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

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

ilkkachu
  • 138,973
2

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
Petr Skocik
  • 28,816
0

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

for d in $(ls -I lib -1 */) ; do cp -R lib "$d" ; done
zentoo
  • 559
  • 5
  • 5
  • 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