| 1 | #!/bin/bash |
| 2 | # Counting to 11 in 10 different ways. |
| 3 | |
| 4 | n=1; echo -n "$n " |
| 5 | |
| 6 | let "n = $n + 1" # let "n = n + 1" also works. |
| 7 | echo -n "$n " |
| 8 | |
| 9 | |
| 10 | : $((n = $n + 1)) |
| 11 | # ":" necessary because otherwise Bash attempts |
| 12 | #+ to interpret "$((n = $n + 1))" as a command. |
| 13 | echo -n "$n " |
| 14 | |
| 15 | (( n = n + 1 )) |
| 16 | # A simpler alternative to the method above. |
| 17 | # Thanks, David Lombard, for pointing this out. |
| 18 | echo -n "$n " |
| 19 | |
| 20 | n=$(($n + 1)) |
| 21 | echo -n "$n " |
| 22 | |
| 23 | : $[ n = $n + 1 ] |
| 24 | # ":" necessary because otherwise Bash attempts |
| 25 | #+ to interpret "$[ n = $n + 1 ]" as a command. |
| 26 | # Works even if "n" was initialized as a string. |
| 27 | echo -n "$n " |
| 28 | |
| 29 | n=$[ $n + 1 ] |
| 30 | # Works even if "n" was initialized as a string. |
| 31 | #* Avoid this type of construct, since it is obsolete and nonportable. |
| 32 | # Thanks, Stephane Chazelas. |
| 33 | echo -n "$n " |
| 34 | |
| 35 | # Now for C-style increment operators. |
| 36 | # Thanks, Frank Wang, for pointing this out. |
| 37 | |
| 38 | let "n++" # let "++n" also works. |
| 39 | echo -n "$n " |
| 40 | |
| 41 | (( n++ )) # (( ++n )) also works. |
| 42 | echo -n "$n " |
| 43 | |
| 44 | : $(( n++ )) # : $(( ++n )) also works. |
| 45 | echo -n "$n " |
| 46 | |
| 47 | : $[ n++ ] # : $[ ++n ] also works |
| 48 | echo -n "$n " |
| 49 | |
| 50 | echo |
| 51 | |
| 52 | exit 0 |