Values rotation in array with bash

Nexy

New Member
Credits
16
Hello


I created a little script that allow to make a rotation of values in an array. The goal was to shift the values to the right and that the last value of the array became the first value in order to create a rotation.

The purpose of the exercice was to do it without using a temporary array but to create a temporary variable in which I can put one of the values of the array then shifted all values to the right and then, put the temporary variable in the array.

Here my script :

Code:
#!/bin/bash

clear
declare -a array

read -rp " How many cases ? " box
read -rp " shift : " n
 
array=( $(seq 1 "$box"))
tmp=${array[-2]}

for((i=$tmp;i>0;i--))
do
     array[$i]=${array[$i -1]}
done

array[0]=$tmp

for((i=0; i<$box;i++))
do
    array[$i]
done

echo " Original array : " ${array[*]}
echo " Temporary variable : " $tmp
echo " Array shifted : ${array[*]}"
But with 2 places to shift, the result is :
Code:
Original array : 9 1 2 3 4 5 6 7 8 9
Temporary variable : 2
Array shifted : 9 1 2 3 4 5 6 7 8 9
Or I want this result :
Code:
Original array : 1 2 3 4 5 6  7 8 9 10
Temporary variable : 2
Array shifted : 9 10 1 2 3 4 5 6 7 8
I can't set up this little script... Can you help me to solve it ?
 


Members online


Latest posts

Top