2011-01-07 64 views
1

在shell脚本我在寻找像我会遍历数组:遍历数组中的蟒蛇做

for i, j in (("i value", "j value"), ("Another I value", "another j value")): 
    # Do stuff with i and j 
    print i, j 

但不能工作了做到这一点的最好方法是什么?我很想重写Python脚本中的shell脚本,但对于我正在尝试的操作来说,这看起来非常沉重。

回答

2

在这种情况下,我会做:

while [ $# -ge 2 ]; do 
    PATH="$1"; shift 
    REPO="$1"; shift 
    # ... Do stuff with $PATH and $REPO here 
done 

注意,每次引用变量($1$PATH ,尤其是[email protected],您想用""引号将它们包围 - 这样可以避免在值中有空格时发生问题。

+1

谢谢,我刚刚意识到什么是一个可怕的想法,它是一个变量称为PATH。 – richo 2011-01-07 10:22:31

0

张贴在这里我用做当前杂牌..

#!/bin/bash 

function pull_or_clone { 
    PATH=$1 
    shift 
    REPO=$1 
    shift 

    echo Path is $PATH 
    echo Repo is $REPO 

    # Do stuff with $PATH and $REPO here.. 


    #Nasty bashism right here.. Can't seem to make it work with spaces int he string 
    [email protected] 
    RAWP=${#RAWP} 
    if [ $RAWP -gt 0 ]; then 
     pull_or_clone [email protected] 
    fi 
} 


pull_or_clone path repo pairs go here 
+0

你可以做`path = $ 1 repo = $ 2;移位2`。 – 2011-01-07 17:18:00

1

有很多方法可以做到这一点。这里有一个使用here doc:

foo() { 
    while IFS=$1 read i j 
    do 
     echo "i is $i" 
     echo "j is $j" 
    done 
} 

foo '|' <<EOF 
i value|j value 
Another I value|another j value 
EOF