Shell – How to Run a command on all subfolders

filesshellwildcards

If you have a series of sub folders (like from a to z) and want to run a command on each one of them (like dsmmigrate * & ) how do you do that? The manual approach would be,

cd a 
dsmmigrate * &
cd ../b

That seems too complicated, so I believe there must be an easier approach.

Best Answer

Yes, changing the working directory back and forth is cumbersome and not really what you would like to do as it can lead to extremely weird situations in more complex scripts, unless you are careful.

The usual method for changing the working directory for a simple command is to put the cd and to invocation of the command in a sub-shell. The working directory will be changed for the sub-shell but the change is not carried over to the rest of the script as the sub-shell is executing in its own environment.

Example: Executing mycommand inside all directories in the current working directory:

for d in *; do
  if [ -d "$d" ]; then         # or:  if test -d "$d"; then
    ( cd "$d" && mycommand )
  fi
done

or in your case, with known directories a and b:

for d in a b; do
  ( cd "$d" && dsmmigrate * & )
done

I don't know the dsmmigrate tool, so I can't say whether running it this way is right or not.

EDIT: It turns out that the dsmmigrate tool has a -Recursive flag:

$ dsmmigrate -Recursive /path
Related Question