sudo su postgres
Having found this closed Question on Stack Overflow and its duplicate, I will post here the solutions found there and there.
➥ You must use the sudo command combined with the su command.
sudo su postgres
When prompted, enter your macOS admin user password rather than the postgres user’s password. At this juncture, your Mac admin user is the one executing the sudo command, not the postgres user.
While I do not understand why we must combine the sudo with the su, it does indeed work for me in macOS Mojave. I did not find this tip among my various BSD and Linux related searching efforts, so perhaps this is a Mac-only Apple thing, perhaps an extra security measure. Or perhaps in the Unix-style OSes, the su command must be run by the root user, and in macOS the root account is disabled by default for security purposes – our Mac admin user account is less powerful than root, and may not be authorized by default to run su? Dunno, don't care, the workaround works.
Modern alternative: sudo -u
According to Craig Ringer and to Erwin Brandstetter, the more modern form is:
sudo -u postgres -i
According to this page:
-u means “run a specified command as this specified user”.
postgres is specifying the username under which we want to run the command.
-i simulates an initial login, meaning the shell will be initialized running that user’s startup scripts.
- No command is provided, so an interactive shell is executed.
For more discussion on the older and newer approaches, see this Question on sister site, What's the difference between sudo su - postgres and sudo -u postgres?. The answer there by Craig Ringer advises: (a) Forget about sudo su, and (b) use sudo -u instead.
Run apps as postgres user
To run a psql session as the postgres user:
sudo -u postgres psql
To run the nano text-editor app as the postgres user:
sudo -u postgres nano