2011-01-07 49 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