Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

I am attempting to compare two strings containing hexadecimal numbers in a dash test, one which has leading zeros and one which doesn't:

hex_string_1: 0x02a0000b
hex_string_2: 0x2a0000b

Trying if [ ${hex_string_1} -eq ${hex_string_2} ] ; then ... (or vice versa, the leading zeros don't seem to matter) gives me this error:

[: Illegal number: 0x02a0000b

Is there a simple way to compare these as numbers, rather than e.g. using sed to reformat the strings?

Since I'm using dash and not bash,[[ isn't an option.

UPDATE: This worked (thanks ott!):

[ $(printf "%d" ${hex_string_1}) -eq $(printf "%d" ${hex_string_2}) ]
share|improve this question
    
Why not just do a string comparison instead? Do you really need an arithmetic comparison if you're just testing equality? –  terdon yesterday
    
-eq is only allowed for for what the shell accepts as an integer. Convert the values with `iv1=$(printf "%d\n" 0x...), then compare. –  ott-- yesterday

2 Answers 2

You could always use printf to convert to decimal and compare that as @ott-- suggested:

[ $(printf "%d" "$hex_string_1") -eq $(printf "%d" "$hex_string_2") ] && echo y

Or

if [ $(printf "%d" "$hex_string_1") -eq $(printf "%d" "$hex_string_2") ]
then
    echo y
fi
share|improve this answer

POSIXly:

[ "$((hex_string_1))" -eq "$((hex_string_2))" ]

With older versions of dash, you needed:

[ "$(($hex_string_1))" -eq "$(($hex_string_2))" ]

POSIXly, AFAICT it's unclear whether:

[ "$hex_string_1" -eq "$hex_string_2" ]

should work or not. The POSIX specification for the [ aka test utility says operands have to be integers, without specifying which forms of integers (decimal, octal, hexadecimal, roman numerals...) are to be supported.

In XCU 1.1.2.1, the reference to C for the utility operands could suggest that hexadecimal or octal constants should be recognised but doesn't state it in so many words.

In practice, [ 0x10 -eq 16 ] only works with posh ([ 0x1 -eq 0x01] works in AT&T ksh (but only because they're treated as 0, [ 0x2 -eq 0x123 ] would return true as well), and except for posh, all [ implementations return false on [ 010 -eq 8 ] (as in 010 is treated as decimal, not octal).

share|improve this answer
    
Posh's test does treat 0x10, 020 and 16 as being pairwise -eq. ATT ksh, mksh, dash, bash, zsh, BusyBox and GNU test all treat 020 as -eq to 20. –  Gilles yesterday
    
Thanks @Gilles, edited in. –  Stéphane Chazelas 14 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.