Linux – Running a Shell Script as a Different User

debianlinuxscriptingshellsuid

What's a good way of running a shell script as a different user. I'm using Debian etch, and I know which user I want to impersonate.

If I was doing it manually, I would do:

su postgres
./backup_db.sh /tmp/test
exit

Since I want to automate the process, I need a way to run backup_db.sh as postgres (inheriting the environment, etc)

Thanks!

Best Answer

To run your script as another user as one command, run:

/bin/su -c "/path/to/backup_db.sh /tmp/test" - postgres

Breaking it down:
 /bin/su : switch user
 -c "/path/to..." : command to run
 - : option to su, make it a login session (source profile for the user)
 postgres : user to become

I recommend always using full paths in scripts like this - you can't always guarantee that you'll be in the right directory when you su (maybe someone changed the homedir on you, who knows). I also always use the full path to su (/bin/su) because I'm paranoid. It's possible someone can edit your path and cause you to use a compromised version of su.