1

bash 4.2

the equation
i=$(( (i+1) %3 ))

I want left i to be 0 when the right i is wrong input like null.

something like i=${((i+3) %3):=0} if I can.

Antonio Petricca
  • 8,891
  • 5
  • 36
  • 74
Lunartist
  • 394
  • 1
  • 3
  • 9

1 Answers1

1

Let's try with:

i=$(( ( ${i-0} + 1) %3 ))

Antonio Petricca
  • 8,891
  • 5
  • 36
  • 74
  • it returns `1` on my system – Lunartist Jul 27 '21 at 07:55
  • Because `1%3` is `1`. – KamilCuk Jul 27 '21 at 08:01
  • I get it. The title was very misleading. My bad. – Lunartist Jul 27 '21 at 08:29
  • `${i-0}` handles only cases where `i` is not set. For example `i=,; echo $(( ${i-0} ))` results in `bash: , : syntax error` and `i=k; k=7; echo $(( ${i-0} ))` prints `7` (note that we used `i=k`, *not* `i=$k`. Inside an arithmetic context variables can be full-blown arithmetic expressions, not just numbers) – Socowi Jul 27 '21 at 09:52