string into variables

Hi,
i am new to Shell Scripting, i want to get some input from user which is string, and i want to store it into variables.

Eg:

str='hello how are you'

i want to store this string into 4variables
lyk s1=hello
s2=how
s3=are
s4=you

thanks,
lak

One way would be

set $str
s1=$1
s2=$2
s3=$3
s4=$4

When the string comes from user input, you could also split the string into words during input, like

read s1 s2 s3 s4

When the user inputs "hello how are you", then s1 becomes "hello", s2 "how", and so on.

if what is the case user gives three word sentence????

eg: how are you

If the user inputs only three words, then they will be assigned to s1 through s3 and s4 will be empty.

And if the user inputs more than four words, then the first three words will be assigned to s1 through s3 and the rest of the line will be assigned to s4.

no no.

my intention is to store string to variables. Is there any command in shell script that i can get only first word in string.

Thanks for reply

With bash or ksh you can write

$ str='hello how are you'
$ echo ${str%% *}
hello

Is that what you need?

Please post your requirement clearly including all possibilities.

Hi,

i am DBA, This is my scenario,
first we have to check how many databases are running in a server..
secondly which database user havn't logged in from last week.

If i have two databases, i'll get 2 parameters output, and want to store in 2 variables to fulfill second requirement.

thanks,
lak

This works for any length string , though not straight forward

#!/bin/bash


str="first second third fourth and so on"

i=1

while [ 1 ]
do
        temp=`echo $str|cut -d' ' -f$i`
        if [ "$temp" = "" ]
        then
                break
        fi
        eval "var_$i"=$temp
        i=`expr $i + 1`

done

for ((j=1;j<=$i;j++))
do
        eval echo '$'var_$j


done

It work fine with more than 2 parameters, if i gave only 1word i.e str="first". it stucked

Try this

#!/bin/bash


str="first second third fourth and so on"

i=1

while [ 1 ]
do
        temp=`echo $str|awk '{print $"'$i'"}'`
        if [ "$temp" = "" ]
        then
                break
        fi
        eval "var_$i"=$temp
        i=`expr $i + 1`

done

for ((j=1;j<=$i;j++))
do
        eval echo '$'var_$j


done


1 Like

Thanks, Problem solved.