Reputation: 133
I am trying to do this...
echo "Enter the number of fruits\n"
read fruit
echo $inp # this will print the number of fruits to enter
if fruit is 4
the script should be able to dynamically ask the user to input [4] fruits and store it into 4 variable like below.
fruit1=apple
fruit2=jack fruit
fruit3=pineapple
fruit4=grapes
i tried the below, but that doesn't help
for i in `seq 1 $fruit`
do
echo "Enter fruit$i\n"
read fruit[$i]
echo "fruit[$i]"
done
Thanks in advance.
Upvotes: 2
Views: 357
Reputation: 5327
This is the ksh88
- and pdksh
-compatible version:
count=4
set -A fruits
i=0
while (( i < count )); do
echo "Enter fruit$i"
read fruits[i]
(( i += 1 ))
done
echo "${fruits[@]}"
Tested with /bin/ksh
(ksh88) on Solaris 8, and pdksh
on MirBSD (whose native mksh
supports the +=()
notation, but on which I have other shells installed for delta testing).
Upvotes: 1
Reputation: 67507
You can grow the array dynamically at each step. Assume you start with the count, initialize the empty array and add elements one by one.
count=4; fruits=();
for i in `seq "$count"`;
do read f; fruits+=( "$f" );
done;
echo "${fruits[@]}"
works in version: Version AJM 93t+ 2010-06-21.
This works with BASH in AIX
Upvotes: 1