Bash – Understanding `echo $((0x63))`

bash

I was searching for a way to convert hexadecimal via command line and found there is a very easy method echo $((0x63)).

It's working great but I'm a little confused as to what is happening here.

I know $(...) is normally a sub-shell, where the contents are evaluated before the outer command.

Is it still a sub-shell in this situation? I'm thinking not as that would mean the sub-shell is just evaluating (0x63) which isn't a command.

Can someone break down the command for me?

Best Answer

$(...) is a command substitution (not just a subshell), but $((...)) is an arithmetic expansion.

When you use $((...)), the ... will be interpreted as an arithmetic expression. This means, amongst other things, that a hexadecimal string will be interpreted as a number and converted to decimal. The whole expression will then be replaced by the numeric value that the expression evaluates to.

Like parameter expansion and command substitution, $((...)) should be quoted as to not be affected by the shell's word splitting and filename globbing.

echo "$(( 0x63 ))"

As a side note, variables occurring in an arithmetic expression do not need their $:

$ x=030; y=30; z=0x30
$ echo "$(( x + y +x ))"
78
Related Question