Port to POSIX shell

So that it can be used on systems without bash / where bash is not used
for startup because of speed.
For variable scoping. Otherwise variables in the function are global across all invocations.