Couldn't php version be set per directory via .htaccess? You wouldn't need that long command then.
Yes, docs do suggest using sudo as web service user so that files get tagged as belong to that user. Wonder what would happen if you didn't use sudo - but root?
Scripts in code/admin/cli/ uses config.php variables ... DB user, DB pass. The error says couldn't clean up temp tables ... which normally are not seen ... does DB user in config have all privs?
I sometimes cheat .... copy the DB user and DB password lines and in those copied lines use root with password for root - commenting out orgininal lines.
When done, revert them back ... comment out root lines ... un-comment original lines.
So it's just one course ... any question types used in this one course different from other courses.
Might install https://moodle.org/plugins/tool_health and run it to see if it complains about question banks.
If the health tool can, it will make suggestions to fix.
'SoS', Ken