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[*]}"
Comment on the previous solution: it allows echo ${array[-i]} because the =( ) splits on IFS i.e. space and newline.
If there is a cyclic shift, the % operator (modulo) is nice!
The following allows a very big (and even negative) shift:
...
# print array[ ] right-shifted by n
print_array_shifted(){
local len=${#array[@]}
local start=$((10*len-n))
local end=$((start+len))
local i
for ((i=start; i<end; i++))
do
echo "${array[i%len]}"
done
}
echo " Original array : ${array
[*]}"
array=( $(print_array_shifted) )
echo " Array shifted : ${array
[*]}"