How to copy using for loop?

6,608

Solution 1

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

Solution 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
Share:
6,608

Related videos on Youtube

the_Strider
Author by

the_Strider

DevOps engineer wannabe kernel programmer.

Updated on September 18, 2022

Comments

  • the_Strider
    the_Strider almost 2 years

    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 ?

  • ilkkachu
    ilkkachu almost 8 years
    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
    ilkkachu almost 8 years
    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).
  • zentoo
    zentoo almost 8 years
    You're right but I have expected that there are only directories in the current path.