SoFunction
Updated on 2025-03-09

Shell uses i++ in loop

Shell uses i++ in loop

In shell scripts, you can use (( i++ )) or let "i++" to increase the value of variable i. This is used to auto-increase the variable i in a loop.

Example of while loop:

#!/bin/bash
# Initialize variable ii=1
# Use a while loop, and execute a loop when i is less than or equal to 5while [ $i -le 5 ]
do
  echo "Loop execution times: $i"
  # Use (( i++ )) to increase i  ((i++))
done
echo "End of loop"

In this example, ((i++)) is used to increase the value of the variable i, and the value of i is increased by 1 each time the loop iteration. You can also use let "i++" to achieve the same effect.

This self-increase method can also be used in the for loop. Here is an example using a for loop:

#!/bin/bash
# Use a for loop, from 1 to 5for ((i=1; i<=5; i++))
do
  echo "Loop execution times: $i"
done
echo "End of loop"

In this example, ((i++)) is used to increase the loop variable i in the for loop.

i++ in shell

I++ operations like ordinary C language are not supported in shells. They are all string operations by default, but the following methods can be used to increase variables themselves

1. Linux uses let to represent arithmetic expressions as follows:

     i=0 
     let i +=1  or let 'i+=1'

2. Let can also be replaced by (()), which is commonly used in for loops.

      ((i++))

Usage in for loop:

((for i=0;i<2;i++))
do
..
done

3. Expr can also be used in linux

      i=`expr $i + 1`;

4. You can also use the following mode

       i=$[$i+1];
       i=$(( $i + 1 ))

This is all about this article about Shell using i++ in loops. For more related Shell loops, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!