Try:
cd RetroPie-Setup
sudo ./retropie_packages.sh hotkeys
Option 3 should do the trick. RGUI opens if you press ESC. Select “Quit Retroarch” to close Retroarch.
Be aware if you plug in a controller with configured hotkeys it is necessary to press the input_enable_hotkey_btn (select) to enable keyboard hotkeys like exit (ESC) or RGUI (F1). Retroarch makes no difference between keyboard keys and joypad buttons.