1

I wanted to rotate element of array in shell script

Array=(11 22 33 44 55)

i tried this

Array[0]=${Array[$3]}

but it is not working, i'm getting array as it was declared.Why?

Finally i got it working as

j=0
k=3
Array[$j]=${Array[$k]}

But question is why can't we pass index directly as i did previously?

1
  • I think you are looking for "shift" – SHW Dec 10 '15 at 10:24
6

ITYM:

Array=(11 22 33 44 55)
Array[0]=${Array[3]}   # "3", not "$3"

Which would have resulted in:

Array=(44 22 33 44 55)

$3 expands to the third positional argument (argument to the shell script), if it's empty (as it usually is in an interactive shell), then ${array[$3]} is the same as ${array[0]} or $array.

If you wanted to achieve:

Array=(55 11 22 33 44)

You'd need to do:

Array=("${Array[4]}" "${Array[@]:0:4}")

Or more generally:

Array=("${Array[@]: -1}" "${Array[@]:0:${#Array[@]}-1}")

With zsh, you could also do:

Array[1,0]=$Array[-1] # insert the last element at the beginning
Array[-1]=()          # remove the last element

or:

Array=("$Array[-1]" "${(@)Array[1,-2]}")

With yash:

array -i Array 0 "${Array[-1]}"
array -d Array -1

With fish (assuming the Array has at least 2 elements):

set Array 11 22 33 44 55
set Array $Array[-1 1..-2]
5
  • In bash-4.2, more generally (and less legibly): Array=("${Array[-1]}" "${Array[@]:0:${#Array[@]}-1}") – mr.spuratic Dec 10 '15 at 10:39
  • @mr.spuratic, good idea, I've added a bash3+ variant of that. – Stéphane Chazelas Dec 10 '15 at 11:03
  • @StéphaneChazelas 'Array[0]=${Array[3]}' wasn't working, i needed to use 'Array[$j]=${Array[$k]}' (variable in place of index), why so? And yes, i wanted to get output as 'Array=(11 22 33 44 55)' 'Array=(55 11 22 33 44)' 'Array=(44 55 11 22 33)' So on – AKASH Dec 10 '15 at 11:30
  • @AKASH. Try Array[0]=${Array[3]} again. It should work. You had Array[0]=${Array[$3]} (note the extra $) in your question which is a no-op. – Stéphane Chazelas Dec 10 '15 at 11:39
  • @StéphaneChazelas yes, it is working, thank you – AKASH Dec 10 '15 at 11:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.