2017-09-25 30 views
0

我想知道在bash中以2或更多的步驟迭代數組的最佳方式是什麼?

例如,以下兩種方法可行,但是最簡單的方法是什麼?Bash - 如何在2的步驟迭代數組?

test_loops.sh

#!/usr/bin/env bash 

function strategyOne() 
{ 
    X=0 
    for I in "[email protected]" 
    do 
    X=$((X%2)) 
    if [ $X -eq 1 ] 
    then 
     B="$I" 
     echo "Pair: $A,$B" 
    else 
     A="$I" 
    fi 

    X=$((X+1)) 
    done 
} 

function strategyTwo() 
{ 
ARG_COUNT=$# 
COUNTER=0 
while [ $COUNTER -lt $ARG_COUNT ]; do 
    let COUNTER=COUNTER+1 
    A="${!COUNTER}" 
    let COUNTER=COUNTER+1 
    B="${!COUNTER}" 

    if [ $COUNTER -le $ARG_COUNT ] 
    then 
     echo "Pair: $A,$B" 
    fi 
done 

} 

echo 
echo "Strategy 1" 
strategyOne $* 

echo 
echo "Strategy 2" 
strategyTwo $* 

生成輸出像這樣:

$ ./test.sh a b c d e 

Strategy 1 
Pair: a,b 
Pair: c,d 

Strategy 2 
Pair: a,b 
Pair: c,d 

回答

1

這裏有一個簡單的方法擊。

#!/bin/bash 

data=("Banana" "Apple" "Onion" "Peach") 

for ((i=0;i< ${#data[@]} ;i+=2)); 
do 
     echo ${data[i]} 
done 

問候!

2

可以使用數組索引使用迭代:

arr=(1 2 3 4 5 6 7 8 9) 

for ((i=0; i<${#arr[@]}; i+=2)); do echo "${arr[i]}"; done 

1 
3 
5 
7 
9 
1

另一種方式來做到這一點:

data=("Banana" "Apple" "Onion" "Peach") 
for i in $(seq 0 2 ${#data[@]}) 
do 
    echo ${data[i]} 
done