有没有办法在bash或zsh中进行“for loop expansion”?

时间:2015-06-23 20:23:40

标签: bash shell for-loop zsh

是否有shell(bash,zsh,??)支持这样的东西?

git branch -D <feature1,feature2,feature3>

这将有效地转变为:

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

2 个答案:

答案 0 :(得分:3)

不,因为这听起来并不像听起来那么有用。大多数命令已经接受多个参数,包括git branch -D

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

不接受此命令的命令通常有充分的理由不这样做。例如,convert "$file" output.jpg具有显式的输出路径,并且天真地循环文件名只会覆盖输出。

对于这些内容,zsh如果有帮助则会有短格式for循环:

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

答案 1 :(得分:2)

##
# 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
}