I'm trying to match exit codes of a process that is documented to return hexadecimal exit codes (e.g. 0x00 for success, 0x40 - 0x4F on user error, 0x50 - 0x5F on internal error, etc.). I'd like to handle the exit code via a case statement, but the "obvious" solution doesn't match:

$ $val = 10

$ case $val in
>   0xA) echo match;;
>   *) echo no match;;
> esac
no match

Is there a readable way to match hexadecimal values in a case statement?


Yes, the double-parentheses arithmetic operator will display hex values as decimal, letting case match them.

$ echo $((0xA))

$ case $val in
>   $((0xA))) echo match;;
>   *) echo no match;;
> esac

You could printf the value to a hex string:

case $(printf '%02x' $val) in
    0a) echo match;;
     *) echo no match;;

This will allow you to match entire classes of error from your application:

case $(printf '%02x' $?) in
    00) echo success;;
    4?) echo user error;;
    5?) echo internal error;;
     *) echo unrecognised error;;

If the process return the string 0x0A, your case will fail then using 0xA. If it is really using numbers, you should use 10 in stead.

  • This doesn't answer the question; clearly I can use 10, but the exit codes are only meaningful in hex. Exit codes are not strings, they'll never be 0x0A. – dimo414 Jul 16 '15 at 1:53
  • Now i understand your question. – Mikkel Alan Stokkebye Christia Jul 16 '15 at 2:01
  • Can you mark the top answer as the answer? – Mikkel Alan Stokkebye Christia Jul 16 '15 at 2:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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