I was writing a Bash script and encountered my first time of integer overflow in Bash. Silence experience, because Bash has no detection for that, no error would be thrown. It took me a few seconds to realize why my script was trapped in endless loop.

I couldn’t find a way to get the value of maximum integer or minimum integer, there was no BASH_INT_MAX to use. Also getconf LONG_MAX resulted in unrecognized variable, LLONG_MAX or ULLONG_MAX don’t work, either, but ULONG_MAX does.

So I wrote one in Bash, the following script could find the values:

#!/bin/bash
# Written by Yu-Jie Lin, Public Domain

for ((i = 1, n = 2;; n = 1 << ++i)); do
  if [[ ${n:0:1} == '-' ]]; then
    printf -- " (2^$i) - 1 = %20s\n" $(((1 << i) - 1))
    printf -- "-(2^$i)     = %20s\n"  $((1 << i))
    exit
  fi
done

With GNU bash, version 4.2.45(1)-release (x86_64-pc-linux-gnu), it returns:

 (2^63) - 1 =  9223372036854775807
-(2^63)     = -9223372036854775808

I don’t think this is a reliable way to find the values.