How to run part of a script with reduced privileges?
You may want to use this trick:
{ anycommand } | su -c 'tee file' user
tee(1)
is POSIX utility, so you may rely on its availability.
Or, with sudo
:
{ anycommand } | sudo -u user 'tee file'
Use a subshell: (su -c 'psql -U postgres -c "<command>"' postgres) > file
Inside the subshell you can drop permissions to do your work, but output is redirected to your original shell which still has your original permissions.