Run sites on git and use many of the scripts in admin/cli/ to either update or upgrade Moodles, but, I run those bash shell scripts as the root user ... not apache user and not under sudo .... and one should probably run them in the moodle code directory. Scripts I have reside else where and cd /pathto/moodle/code/ before doing anything else.
Could be the environment of the apache user is the culprit ... server have some other protections running like seLinux or apparmor, etc.? Running safe mode?
https://www.acunetix.com/websitesecurity/php-security-5/
'spirit of sharing', Ken