read n number of inputs

Hello,

I think its a sinple query but somehow i m stucked up here...

I am trying to enter n number of inputs from the user and write them in
an input file ie row wise...

I tried standard commands like

$echo "enter the inputs for the file"
$read var1 var2 var3 var4
test1 test2 test3 test4
$echo "$var1\n$var2\n$var3\n$var4" > input_file
$more input_file
test1
test2
test3
test4

However, the problem lies that i dont know how many inputs the user wants to enter
like
here we have 4 inputs but it may be 5,6 .... and so on...
so if we write till var4 it will not take var5 and var6....

Pls suggest where i am wrong or the possible solution...

Thakns In advance
Aparna

man 1 getopt
i=1
while true
do
   read var
   [ "${var}." = "." ] && break; #NULL VAR->STOP INPUT
   VAR[${i}]=$var
   (( i += 1 ))
done

# to show

j=1
while [ ${j} -lt ${i} ]
do
   echo ${VAR[${j}]}
   (( j += 1 ))
done

What about this?

#!/bin/bash

read var

declare -a vars

vars=($var)

echo Number of elements: ${#vars[*]}

echo Elements:
j=0
while [ ${j} -lt ${#vars[*]} ]
do
   echo ${vars[${j}]}
   (( j += 1 ))
done

Regards.

getopt is useful when there is a need to parse command line arguments and in this case it would not work.

Thanks a lot for the solution . However, can there be some possibility , that by using ksh !!!

I dont want to use bash shell....

Thanks a lot for help!!

Try this:

#!/usr/bin/ksh

echo "Enter the inputs for the file: \b"
read input
echo $input |tr ' *' '\n' > input_file

You just read one variable.

#!/usr/bin/ksh

read var

set -A vars $(echo $var)

echo Number of elements: ${#vars[*]}

echo Elements:
j=0
while [ ${j} -lt ${#vars[*]} ]
do
   echo ${vars[${j}]}
   (( j += 1 ))
done

This is ksh:

Klashxx,

     every where \{ \} are used is there any specific reason .. i tried the script with no \{\} i got error 

line 1: var: command not found

can u explain me

--Chanakya

I simulated your issue ,but i didn�t get the same result.
What shell are you using? Could you post what you tried?

Thx

I think the reason for the error is that "{}" are mandatory for arrays but not for "normal" variables.
In assignments its OK:

VAR[${i}]=$var

But, here, you need the "{}":

# Right
echo ${VAR[${j}]}

# Wrong
echo $VAR[${j}]

Regards.

Thanks Grial .. now i got it thanks a lot..

-Chanakya

There is another method but in this method we need to answer y or n if we want to give more output.

echo "enter the inputs for the file"
answer=y
while [ "$answer" = "y" ]
do
read fname
echo "$fname">>filename
echo "Enter anymore y or n\c"
read anymore
case $anymore in
y*|Y*) answer=y ;;
n*|N*) answer=n ;;
*)answer=y ;;
esac;done

Another solution :

echo "Enter values, finish with CTRL/D :"
cat - >input_file

Jean-Pierre.