How to swap the values in array using for loop?

array=( 8 5 6 2 3 4 7 1 9 0 )
for i in "${array[@]}"
do
echo $i
done

# i need the output like this by swapping of array values

0
9
1
7
4
3
2
6
5
8

What shell are you using?

What are you trying to do? Are you trying to rearrange the elements of your array? Or are you just trying to print the array in reverse order?

i am using bash shell v-4.2
i just need to rearrange the elements of my array & tell me how to print in reverse order

array length can be retrieved as ${#array[@]}

for (( index=${#array[@]}-1 ; index>=0 ; index-- )) ; do
    echo "${array[index]}"
done
1 Like

It would be much easier to print your array in forwards order than to reverse the order of your array and then print it in reverse order. Why is there is any need to reverse the order of array elements AND print the array in reverse order??? The code you showed us in post #1 in this thread produces the output that would produce.

Thankz buddy! its working

The code itkamaraj gave you will print the array in reverse order. If you need to reverse the order of elements in the array, there are a couple of ways to do it.

The following will work with arrays like your sample that only have single word elements:

array=( $(for ((i = ${#array[@]} - 1; i >= 0; i--)) 
	do	printf '%s\n' "${array[$i]}"
	done)
)

but won't work if you have one or more elements that contain multiple words, such as:

array=( 8 5 6 2 3 "4 and more" 7 1 9 0 )

To reverse an array like this, you can use something more like:

for ((i = 0; i < ${#array[@]}; i++))
do	tmp_array="${array[${#array[@]} - 1 - i]}"
done
array=( "${tmp_array[@]}" )
unset tmp_array

For single digit array elements, would this do?

echo ${array[@]} | rev
0 9 1 7 4 3 2 6 5 8

For Don Cragun's multi word example, would this do?

printf "%s\n" "${array[@]}" | tac
0
9
1
7
4 and more
3
2
6
5
8