Perform an action in every sub-directory using Bash

Viewed 212161

I am working on a script that needs to perform an action in every sub-directory of a specific folder.

What is the most efficient way to write that?

10 Answers

if you want to perform an action INSIDE the folder and not ON folder.

Explanation: You have many pdfs and you would like to concetrate them inside a single folder. my folders

   AV 001/
   AV 002/
  • for D in *; do cd "$D"; # VERY DANGEROUS COMMAND - DONT USE #-- missing "", it will list files too. It can go up too.
  • for d in */; do cd "$d"; echo $d; cd ..; done; # works succesfully
  • for D in "$(ls -d */)"; do cd "$D"; done; # bash: cd: $'Athens Voice 001/\nAthens Voice 002/' - there is no such folder
  • for D in "$(*/)"; do cd "$D"; done; # bash: Athens Voice 001/: is folder
  • for D in "$(`find . -type d`)"; do cd $D; done; # bash: ./Athens: there is no such folder or file
  • for D in *; do if [ -d "${D}" ] then cd ${D}; done; # many arguments
Related