Linas
Linas

Reputation: 602

Shell programming: nested expressions with command substitution

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?

Upvotes: 3

Views: 2691

Answers (2)

Jens
Jens

Reputation: 72707

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.

Upvotes: 7

Igor
Igor

Reputation: 1855

You can use

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

${#number}

can be used to retrieve length of string

Upvotes: 1

Related Questions