Practice Exercise in Bash Basics Series #5: Using Arrays in Bash

If you are following the Bash Basics series on It’s FOSS, you can submit and discuss the answers to the exercise at the end of the chapter:

Fellow experienced members are encouraged to provide their feedback to new members.

Do note that there could be more than one answer to a given problem.

#!/bin/bash

numbers=()

read -p "Enter 3 numbers: " num

IFS=' ' read -r -a numbers <<< "$num"

numbers_length=${#numbers[@]}

reverse_numbers=()

for (( i=$numbers_length-1; i>=0; i-- )); do
        reverse_numbers+=("${numbers[i]}")
done

echo "Numbers in reverse order are: ${reverse_numbers[*]}"

I liked the use of IFS. I guess I deliberately omitted that from the tutorial.

1 Like

another way to only litmit within the scope of that article, please

I still barely understand $IFS - but it gets me every time when I try to use a 2D range of values in a “for loop” - so I then have to “IFS=$'\n” when it gets unhappy :smiley:
$IFS has been tripping (sic) me up for years…

My first script for #2 was

#!/bin/bash

echo “Number reversal Exercise”

read -p "enter first number: " num1
read -p "enter second number: " num2
read -p "enter third number: " num3

reverse_number=($num3 $num2 $num1)

echo “The reverse order of numbers entered is ${reverse_number[*]}”

And then I saw the expected output and changed it to

echo “Number reversal Exercise”

echo "Enter three numbers and press enter: "
read -p “–>” num1 num2 num3

reverse=($num3 $num2 $num1)
echo “The reverse order of numbers entered is ${reverse[*]}”

By the way, Thank you Abhishek Prakash for this tutorial, I am learning so much from this.

1 Like