Question

I have trouble handling expressions within other expressions. For example, here's my code:

 #!/bin/sh
 number=0
 read number
 if [ `expr substr $number 1 2` = "0x" ]; 
 then
 echo "Yes that's hex: $number"
 number=`expr substr $number 3 `expr length $number`` 
 echo $number
 else
 echo "No that's not hex"
 fi

all I want is for echo to print the number without '0x'. Let's say if the input is 0x15 the output should be just 15. But it seems that finding the length of the string fails.

Now if I create another variable named length like this:

 #!/bin/sh
 number=0
 read number
 if [ `expr substr $number 1 2` = "0x" ]; 
 then
 echo "Yes that's hex: $number"
 length=`expr length $number`
 number=`expr substr $number 3 $length` 
 echo $number
 else
 echo "No that's not hex"
 fi

it works.

So how to get the same result without creating another variable?

Was it helpful?

Solution

If your shell is POSIX (most are these days, except Solaris' /bin/sh), you can nest what is called command substitution with $(), eg.

number=$(expr substr $number 3 $(expr length $number))

Command substitution with nested backticks requires ugly layers of backslash escaping.

OTHER TIPS

You can use

number=`expr substr $number 3 ${#number}`

${#number}

can be used to retrieve length of string

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top