Validate numeric input and bases
Bash interprets integer constants beginning with 0 as octal and 0x as hexadecimal. It also accepts base#digits, for example 2#101 or 10#08. An arbitrary string is not automatically a safe number: arithmetic evaluates variable contents as expressions, not simply as decimal text. Before evaluating external input, define a narrow contract, validate the entire string, and bound its length. The examples accept only one to six ASCII decimal digits under the C locale (0 through 999999, with leading zeros allowed). Then 10#$raw explicitly selects decimal. This contract intentionally rejects signs, spaces, expressions, and longer numbers. For signed input, design a separate sign-handling and range-validation step; do not blindly prefix negative strings with 10#. Use fixed trusted expressions, not user-supplied arithmetic programs. For a signed decimal contract, first validate the entire string and bound its magnitude, then separate the optional sign from the digit sequence. Apply 10# to digits only; for example, the fixed expression $(( -(10#08) )) evaluates to -8.
Practical examples
Run each example separately in Bash 5.2 in a fresh empty practice directory. Tests use default shell options and C locale; the fractional lesson requires awk. Output is shown separately; do not enter it as code.
Read constants in different bases
printf '%s\n' "$(( 010 ))" "$(( 0x10 ))" "$(( 2#101 ))" "$(( 10#08 ))"Expected stdout:
81658The notation determines the base, not the output format.
Validate then convert
export LC_ALL=Craw=00042if [[ $raw =~ ^[0-9]{1,6}$ ]]; then printf '%s\n' "$(( 10#$raw ))"else printf '%s\n' invalidfiExpected stdout:
42The anchored pattern bounds the accepted digits before decimal conversion.
Reject an expression
export LC_ALL=Craw='2+3'if [[ $raw =~ ^[0-9]{1,6}$ ]]; then printf '%s\n' "$(( 10#$raw ))"else printf '%s\n' invalidfiExpected stdout:
invalidThe plus sign violates the input contract; the arithmetic branch is never evaluated.
Common mistakes
08 is not valid octal. Merely quoting a value inside arithmetic does not validate it. Never pass arbitrary input directly to arithmetic expansion, let or an integer attribute assignment.
Practice
Apply the one-to-six-digit contract to 00042, 0, 999999, 1000000, -2, and 2+3. Accept the first three as 42, 0, and 999999; reject the rest before arithmetic.
Next: Fractional calculations with external tools