문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

You can use

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

${#number}

can be used to retrieve length of string

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top