Values rotation in array with bash

Hello :slight_smile:

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 :

#!/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 :

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 :

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 ?

Welcome to the forum.

Is that a homework / classwork assignment?

Yes, absolutely.

The purpose of the exercice is to be able to manage array ( in C# normally ). I'm able to do this exercice in C#, but I preparing my self to becoming an Linux system-administrator so I learn to use bash script. I have the possiblity to use this sript language in class, so I want to know how to do this exercice with bash.

It's possible to help me for this ?

There's a special subforum: Homework & Coursework Questions - UNIX and Linux Forums.
Please reopen your request there, filling in the entire form.
Thanks.

1 Like