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.

6
  • What do you mean wrong input? Commented Jul 27, 2021 at 7:58
  • right i can be empty or have trash values Commented Jul 27, 2021 at 8:08
  • Then you validate i first, and then do the calculation and the assignment. Commented Jul 27, 2021 at 8:09
  • I was trying to do the validating by setting the default value thus this question Commented Jul 27, 2021 at 8:11
  • 1
    No, I don't think that'll work. You should either declare i as an integer beforehand (declare -i i) so that it can't be assigned trash, or validate its value using a case or [[ command first. Commented Jul 27, 2021 at 8:14

1 Answer 1

1

Let's try with:

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

Sign up to request clarification or add additional context in comments.

4 Comments

it returns 1 on my system
Because 1%3 is 1.
I get it. The title was very misleading. My bad.
${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)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.