Skip to content
shellhacks.dev
Shell Scripting

Increment a counter in POSIX sh

Increment a counter in POSIX sh with i=$((i + 1)). The i++ and let forms are Bash and ksh extensions that dash reports as command not found.

1 min read
Summarize in AI

A loop counter in a #!/bin/sh script is built with arithmetic expansion, because the shorter forms from Bash are not portable.

Shell
i=0
i=$((i + 1))
i=$((i + 1))
echo "i is $i"
i++
let i=i+1
(( i++ ))
Text
i is 2
main.sh: 5: i++: not found
main.sh: 6: let: not found
main.sh: 7: i++: not found

$((expression)) is arithmetic expansion, defined in POSIX, and it works in every conforming shell. The three failed lines at the end show what Debian's dash does with the other forms: it looks for a command named i++ or let, and it reads (( as two nested subshells.

Arithmetic expansion is signed integer only, and inside it variables need no dollar sign. The postfix increment inside it, as in $((i++)), is not guaranteed by POSIX, so keep the assignment form.

Share

More snippets

Shell Scripting

Test for a prefix without double brackets

Test for a prefix in POSIX sh with a case pattern such as release-*), which works in dash and every other shell where double brackets are a syntax error.

1 min read
Shell Scripting

Check if a command exists in POSIX sh

Check that a command exists with command -v in POSIX sh. It is a builtin, it sees functions and builtins, and which does not.

1 min read
Shell Scripting

Replace an array with positional parameters

POSIX sh has no arrays, but set -- a b c turns the positional parameters into one, and "$@" expands each element as its own word without splitting.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.