Seems to have fixed the issues, with help from shellcheck.net and IRC