If you want a one liner for this to stuff in a test or subshell or something, this works well:
ps -ef | egrep '(httpd|apache2|apache)' | grep -v "$(whoami)" | grep -v root | head -n1 | awk '{print $1}' | groups | awk '{print $2}'
In the above, the last command selects the 2nd group, because the first is typically sys
, which is not generally useful.
If you want a list of all groups that apache is in, drop the last pipe section awk '{print $2}
, like so:
ps -ef | egrep '(httpd|apache2|apache)' | grep -v "$(whoami)" | grep -v root | head -n1 | awk '{print $1}' | groups
If you want the apache username, do the previous and also drop the groups
pipe section, like this:
ps -ef | egrep '(httpd|apache2|apache)' | grep -v "$(whoami)" | grep -v root | head -n1 | awk '{print $1}'
I do not suggest making assumptions about the environment unless it is fully under your own control. If you need to programmatically determine the user and are not absolutely certain that it will always run in a specific environment (or are not certain that someone may have changed it to some custom name/group in their apache.conf), then it is practical to have some uniform method to check for it. You can stuff this in a .env
file under some common key for localized program access, or alternately echo it into bash_profile
or bashrc
if you want a consistent variable to check systemwide, perhaps like this:
echo export "WEBSERVER_USERNAME=$(ps -ef | egrep '(httpd|apache2|apache)' | grep -v "$(whoami)" | grep -v root | head -n1 | awk '{print $1}')" >> ~/.bash_profile
echo export "WEBSERVER_USERGROUP=$(ps -ef | egrep '(httpd|apache2|apache)' | grep -v "$(whoami)" | grep -v root | head -n1 | awk '{print $1}' | groups | awk '{print $2}')" >> ~/.bash_profile
source ~/.bash_profile
Elsewhere: ...
# chown a dir to the webserver universally
# for typical 755 directory permission
# Good for production environment web app folders
sudo chown "${WEBSERVER_USERNAME}:${WEBSERVER_USERGROUP}" /path/to/dir
# chown to your user and the webserver usergroup
# for shared 775 cli/http directory perms
# good for dev environment, localhost, or anywhere that
# you have to do a lot of cli file edits to web folders/files
sudo chown "$(whoami):${WEBSERVER_USERGROUP} /path/to/dir
or whatever else you need it for without having to look it up a million times