problem with expr command

:slight_smile:
hi Unix gurus,
Pls consider the following piece of code
str='hello'
length=echo $str|wc -c
echo $length
y= ` expr \( 80 - $length \) `
echo $y
:confused:
The last echo stmt is displaying 0 as the result.
If i put direct value like 6 instead of $length in i 3rd stmt it is giving the correct result.
I came to know that $length is not getting accessed inside of expr command.

any help pls.

cheers
Ravi Raj Kumar

You are not assigning value to variable length correctly, try using backquotes there as well

length=`echo $str|wc -c`

Another way of doing it (bash)

str='hello'
length=${#str}
y=$(( 80 - $length ))

:slight_smile:
hi Ripat,
Thank u for ur reply.The method u suggested is working fine.
But i want it to be worked in the following way.

str='hello'
length=`echo $str|wc -c`
echo $length
y= ` expr \( 80 - $length \) `
echo $y

cheers
Ravi Raj Kumar

str='hello'
length=`echo $str|wc -c`
echo $length
y=`expr 80 - $length`
echo $y

try this

y=`expr 23 - $length`

:slight_smile:

Fine the above code is working.
But i wonder that ,why its not giving result,if we put parantheses.
we must to put parantheses in arithmetc expressions na.
suppose we have a long expression like 10 + 20 -30 + 40 *2 ,then will the above technique works :confused:

any help pls

cheers
Ravi Raj Kumar :slight_smile:

expr 10 + 20 - 30 + \( 40 \* 2 \)

This works if you give a space between operator and operand

y=`expr \( 23 - $len \)`

you can also use let

let " y=(80-$x)*10/2+$c " etc. between " " just aritmetical operations no ekstra things.