I'm trying to write a shell script which should work under any POSIX shell, and I found what seems to be an odd quirk of
dash. I'm wondering whether this is something I can rely on working under other POSIX compatible shells, or whether it is simply an unintentional feature of the
In an arithmetic expansion a variable can be written either with or without the inital dollar sign (except in the case of the positional parameters, which must always be written with a dollar sign,
But I've found that the behaviour of
"$((X))" is different from
"$(($X))" in that
"$(($X))" seems to be expanded twice, rather than just once. I.e. if my variable
X contains the name of another variable (
X=Y), which in turn contains a numeric value (
"$(($X))" will return
"$((X))" will just produce an 'Illegal number: Y' error.
Can I rely on this behavior being the same in other POSIX shells?
The odd behavior
"$(($X))" do not behave the same.
$ X=Y; Y=1 $ echo "$((X))" dash: 1: Illegal number: Y $ echo "$(($X))" 1
Just for completeness I here include what with no indirection and two layers of indirection. With no indirection everyting works as expected:
$ X=1 $ echo "$((X))" 1 $ echo "$(($X))" 1
As expected, two layers of indirection does not work (though notice that the error messages are referring to different values).
$ X=Y; Y=Z; Z=1 $ echo "$((X))" dash: 6: Illegal number: Y $ echo "$(($X))" dash: 7: Illegal number: Z
This question is somewhat related to this question about Arithmetic expansion and parameter expansion but it’s not the same since that's dealing with the behaviour of
bash and more advanced shells, but I'm wondering about expected POSIX behavior.