@CapNinja
I suggest it can be the timer that leads to such behaviour. After 3s of waiting if the PID is active then a kill term 9 is send to process. That leads to a process abort. You can try to extend the time by changing the sleep command or by changing the number counter. I get some obscure errors if a process was terminated with siglevel 9.
No I don't think it has something to do with the script. Sounds like problem with data access from KODI.
Suddenly is a kind of magic, too.
You wrote you use a pendrive, which can lead to problem 2 - writing cache for KODI. KODI responds sometimes slow on pendrives esp. with ntfs format
Unrelated to script.
All in all I think you might get some problems with the powering and the pendrive. To be sure I would extent the sleep timer from 0.1 to 0.25 be aware that a not closing process needs now 30x0.25s time ~ 8s to be forced closed now.
Maybe you can give feedback to this later ;)
@Efriim retropie-setup dialogs can't be closed. As long as the call was initiated by runcommand shell script then every script or binary can be closed. If the runcommand call is missing then there is no pathway for the close switch.