Search code examples
shellnestedexpressioncommand-substitution

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?


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.