0

I have an array that consists of the following: -

d23 d3 d21 d1 d20 d0 d26 d6

I want to repeat the same for every two elements of the array. For example:

echo d23 d3

And then move on to the next two elements:

echo d21 d1

I've attempted a combination of while loops and shift to avail. Any help and advise would be much appreciated.

3 Answers 3

3

Just loop through them:

a=(d23 d3 d21 d1 d20 d0 d26 d6)

$ echo ${#a[@]}
8

$ for (( i=0; i<${#a[@]}; i+=2 )); do echo "${a[$i]} ${a[$i+1]}"; done
d23 d3
d21 d1
d20 d0
d26 d6
Sign up to request clarification or add additional context in comments.

Comments

2

If you have your heart set on using shift note that it only works on the positional parameters, so you could use it in a function:

print_pairs () {
    while [ $# -gt 0 ]; do
        echo $1 $2;
        shift 2;
    done
}

a=(d23 d3 d21 d1 d20 d0 d26 d6)
print_pairs "${a[@]}"

Comments

0

A variation of ooga's version with recursion:

a=(d23 d3 d21 d1 d20 d0 d26 d6)
pp () 
{ 
  [ $# -lt 2 ] && return
  echo $1 $2
  shift 2
  pp $@
}

pp "${a[@]}"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.