ptkvsk
ptkvsk

Reputation: 2222

Run arbitrary zsh command for all subfolders

I'm currently using this function to run a command for all subfolders in zsh.

forsubdirs() {
   for dir in *; do
     (cd ${dir} && echo $fg_bold[yellow]${PWD##*/}$reset_color && $@ && echo '\n')
   done
}

I use it like this: forsubdirs git pull The problem, though: it does not work with aliases. How to execute an arbitrary ZSH command (including aliases and lists of commands separated with "&" or ";") for all subfolders?

Upvotes: 0

Views: 115

Answers (1)

Adaephon
Adaephon

Reputation: 18329

In order to be able to pass complex commands as argument you need to quote syntactic elements like ; and &. The arguments then need to be explicitly evaluated with the eval command. For example:

forsubdirs () {
    for dir in *(/) ; do
        ( cd $dir && echo $fg_bold[yellow]${PWD##*/}$reset_color && eval $@ && echo '\n' )
    done
}

forsubdir 'ls -1 | sed "s/^/    /"'

Also, I would suggest using *(/) instead of plain *. It matches only directories, so that the function does not even try to run cd on regular files.

Upvotes: 1

Related Questions