Storing the output into a variable

Hi unix gurus,

I am trying to store the result of a command into a variable.
But it is not getting stored.

x='hello'
y=echo $x | wc -c

but it is giving the output as 0(zero)

Pls help me its very urgent

x='hello'
y=$(echo $x | wc -c)

:slight_smile: Ok,fine .Its working.But when i am trying to use the result in another calculation its not giving the proper result.
x='hello'
y=$(echo $x | wc -c)
echo $y
z='expr $y + 1 '
echo $z

Its printing expr $y + 1 instead of 7. :confused:

any idea pls.

cheers
Ravi Raj kumar

can you try back quotes instead

z=`expr $y + 1`

:smiley:
Thank u so much boss.Its working now fine.

Thanks a lot.

cheers
Ravi raj kumar

You need to understand the difference between

y=$(echo $x | wc -c)
and
z='expr $y + 1 '

In y=$(echo $x | wc -c), the output of the command echo $x | wc -c is stored into y. It is known as command substitution. You can do a command substitution in two ways. Either use $(...) or `...`

In z='expr $y + 1', the string expr $y + 1 is stored in z without any literal expansion.

The script works if you have the correct quote marks around the z='expr $y + 1 '. It is not the single quote ' but the backward quote` very important! I have tested it just to make sure!!!

They are called "backticks" and makes the script to interpret it as a shell command passed directly via CLI.
Example :

for i in `sec 1 200` do cat $i