(Warning pedantic script review)
Add a "set -e" to catch errors. Say if the disk can't be read or file can't be written.
Why reuse the same temp file? Make a new one with mktemp and auto clean it via an exit trap. As it's written this isn't concurrently safe.
Exiting -1 on error? Don't use negatives.
Wrap it all in a main() function and use locals instead of global vars.