I can run commands like vacuumdb, pg_dump, and psql just fine in a script if I preface them like so:
/usr/bin/sudo -u postgres /usr/bin/pg_dump -Fc mydatabase &g
databases=psql -h localhost -U postgres -q -x -t -c "\l" | grep 'Name' | sed 's/ //g' | sed 's/Name|//g'
psql -h localhost -U postgres -q -x -t -c "\l" | grep 'Name' | sed 's/ //g' | sed 's/Name|//g'