Store user input in differ

Hello all

Can anyone help me to solve the below issue

I want to take user input with space separated .The number of inputs can be variable

like if user inputs
1 2 3 4

ouput will stored in as array a [i]where i=4 and I can retreive the value like a[3] =3

any thoughts how to do it

Appreciate your kind help

what language/shell/OS ?

try justdoit codes :wink:

# ./justdoit
Please give your value(s) [ 1 2 3 4 ] ? 1 3   5
Please only give an input value for [1 2 3 4] with space!!

Please give your value(s) [ 1 2 3 4 ] ? 1      5
Please only give an input value for [1 2 3 4] with space!!

Please give your value(s) [ 1 2 3 4 ] ? 1             2
Enter the values in 'a space' between them

Please give your value(s) [ 1 2 3 4 ] ? 4 1 3
1.val="4"
2.val="1"
3.val="3"
## justdoit ## unix.com @ygemici
#!/bin/bash
while :; do
read -p "Please give your value(s) [ 1 2 3 4 ] ? " i
if [ -z "$i" ] ; then echo "Please give an input value for [1 2 3 4] with space!! "
elif [[ $(echo "$i"|sed 's/ /\n/g'|grep -wv '[1-4]') ]] ; then
echo "Please only give an input value for [1 2 3 4] with space!! "
elif [[ $(echo "$i"|grep '  ') ]] ; then
echo "Enter the values in 'a space' between them"
else
ttn=$(echo "$i"|sed 's/ /\n/g'|sed -n '$=')
rrc=${#ttn[@]}
case $rrc in
1|2|3|4)a=($(echo "$i"|sed 's/ /" "/g;s/$/"/;s/^/"/'));;
*)echo "incorrect usage!!" && exit 1;;
esac;break
fi;done
for((j=1;j<=${#a[@]};j++));do
aa[j]=${a[j-1]}
echo "$j.val=${aa[j]}"
done

regards
ygemici

1 Like