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
Related videos on Youtube
![the_Strider](https://i.stack.imgur.com/xMAJl.jpg?s=256&g=1)
Comments
-
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 almost 8 yearsThat
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 ignorelib
because it's given on the command line, through the glob (tryls -l -I lib lib
). And parsing ls like that will burn if you have filenames with spaces. -
ilkkachu almost 8 yearsyou could get close with
ls -I lib .
orls -d -I lib */
, but you get either regular files too (which*/
doesn't give), orlib/
too (since it's in the glob). -
zentoo almost 8 yearsYou're right but I have expected that there are only directories in the current path.