This totally makes sense in mksh only.

$ i=4+4; echo $i

This is an assignment of the string "4+4" to the variable i. The string
is then, between assignment and storage, parsed as an arithmetic
expression, because i is of integer type. The expression is calculated
and the result stored.

$ i=i+1; echo $i

This is an assignment of the string "i+1" to the variable i. The string
is then, between assignment and storage, parsed as an arithmetic
expression, because i is of integer type. The expression is calculated
and the result stored.

This works because i=anything, if i is integer, is precisely the same as
i=$((anything)).

$ i+=1; echo $i

This is an assignment of the string “${i}1” to the variable i. The
string is first expanded as "11", then evaluated as an arithmetic
expression, and the result (the number 10#11) stored. This is the same
as: i=$((${i}1)).

“var+=text” is the same as “var=${var}text”. This is the basic tenet,
and this is the thing that will not change. (I am now decided.) The
other mentioned shells do this wrong. (This is one thing I will not
budge for cross-shell consistency.)

It’s much easier to accidentally introduce an error with += forgetting
that the target variable is integer (the integer flag may even have been
set by a caller!) than not using proper integer arithmetics.

Just write one of these:

$ let i+=1; echo $i
$ (( i += 1 )); echo $i
$ (( ++i )); echo $i
$ echo $((i+=1))

These should work the same in all shells mentioned.

At that: if a *caller* passes you an integer variable, in all other
shells you cannot use “+=”, which means you cannot use “+=” in the other
shells reliably at all.

function strconcat {
        nameref _strconcat_tgt=$1
        _strconcat_tgt+=$2
}
typeset -i foo=1
strconcat foo 2

Bam!

-- 
You received this bug notification because you are a member of mksh
Mailing List, which is subscribed to mksh.
Matching subscriptions: mkshlist-to-mksh-bugmail
https://bugs.launchpad.net/bugs/1857702

Title:
  " +=" operator does string concatenation for integer variables

Status in mksh:
  Fix Committed

Bug description:
  consider

  typeset -i x=0; x+=1; echo $x # → 1 (as in ksh/bash/zsh)

  but

  typeset -i x=1; x+=1; echo $x # → 11 (rather than 2 as in the other
  shells)

  I believe mksh should honour the integer declaration and interpret
  `+=' accordingly. currently, it does not even consistently use string
  concatentation (since the first example does not yield `01' ...).

To manage notifications about this bug go to:
https://bugs.launchpad.net/mksh/+bug/1857702/+subscriptions

Reply via email to