Is there a way to do "for loop expansion" in bash or zsh?

253 Views Asked by At

Is there a shell (bash,zsh,??) that supports something like this?

git branch -D <feature1,feature2,feature3>

that would effectively make a transformation to:

for BRANCH in feature1 feature2 feature3; do git branch -D $BRANCH; done
2

There are 2 best solutions below

3
On
##
# Run the given command (first args up to `--`)
# on each of the following args, one at a time.
# The name `map` is tongue-in-cheek.
#
# Usage: map [cmd] -- [args]
map() {
    local -a cmd
    local arg
    while [[ $1 ]]; do
        case "$1" in
            --) break;;
        esac
        cmd+=( "$1" )
        shift
    done
    shift
    for arg; do
        "${cmd[@]}" "$arg"
    done
}
2
On

No, because this is not nearly as useful as it sounds. Most commands accept multiple arguments already, including git branch -D:

$ git branch -D foo bar baz
Deleted branch foo (was 9e9d099).
Deleted branch bar (was 9e9d099).
Deleted branch baz (was 9e9d099).

Commands that don't accept this typically have a good reason not to. For example, convert "$file" output.jpg has an explicit output path, and naively looping over filenames would just overwrite the output.

For these things, zsh has short form for loops if it helps:

for f (foo bar baz) convert "$f.png" "$f.jpg"