ksh: := doesn't work as expected
$ typeset -i a b=42
$ echo ${a:=b}
0 # expecting `42', or at least `b'
$ echo $a
# definitely expecting `42', zsh prints `0' here
$
This works fine on mksh, and partly on bash.
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 18
@McDutchie Can’t find a flaw, thanks for the fix
@McDutchie - you are right. That means that whenever
typeset -i a; a="something"
“something” should be evaluated as an arithmetic expression, for example like this (this works):Now I begin to think that problem is somewhere else:
Looks like sometimes (? modifier, :? modifier, := modifier)
a
is assumed to have a zero integer value, otherwisea
is unset. We simply do not reach the assignment phase because because ksh concludeda
already has a value (well, sometimes)This is going off topic, but I was referring only to what I quoted, not the
:=
part. I.e. even the most basic form of an assignment likea=b
can takeb
literally (posix) or as$b
(ksh whena
is an integer - which might have been set elsewhere at the code). That’s the part I was referring to.The
:=
behavior is an obvious extension of the basic rule quoted earlier that value assigned to an integer var is evaluated as an arithmetic expression.FWIW, this behavior, e.g.
typeset -i a; b=5; a=b; echo $a
works the same and prints 5 also in bash and mksh (both even in posix mode) and in other pdksh derivatives like pdksh itself and openbsd sh.@avih Actually, POSIX leaves room for such extensions.
I do not agree, because in the reproducer, that variable has been declared an integer with
typeset -i
. And that means assignment values for that variable are parsed as arithmetic expressions, even without$((
…))
being used. In arithmetic expressions, variable names that are not expanded by the shell (i.e. those without a leading$
) are replaced by their numeric values by the arithmetic subsystem. So, for ana
of an integer type, a simple assignmenta=b
will assign the numeric value ofb
toa
. Since${a:=b}
and${a=b}
are just another form of assignment (though they are performed conditionally and yield a value), they should work the same way.Compare with mksh, which does this right:
Confirmed on all versions of ksh93 down to s+ 1993-12-28 through ksh2020. Anther one that is going to be challenging to track down… Thanks for the report.