Normally i would google, but I did not know how to google the problem I am facing now also being a newbie in shell scripting.

Okay, the requirement is
user1 has sudo rule to su - user2(NO PASSWORD) and user2 has will be able to sudo certain commands

so following works fine from command prompt

user1@host] sudo su - user2

the above command opens up a new shell, logging me in as user2

user2@host] sudo cmd1
user2@host] sudo cmd2
user2@host] sudo cmd3
user2@host] exit

How would I achieve the above using a shell script?

I have tried putting following commands in a shell script

sudo su - user2 -c "sudo cmd1" (this prompts me for a password though I have a sudo rule to not prompt for one.)

sudo su - user2 (this gets me out of the shell and takes me to "user2@host]")

none works for me.
Any help on this would be greatly appreciated.


SUDO is to make you have root privileges for executing the script you are about to run not really used for switching to a different user. There are other options. Linux allows you to set up a script so that when it is run it appears to be run by the owner of the file. You will see these in various place throughout the file structure. As an example the mount command in the list below has this set (execute permission for owner shows "s" instead of "x") and it is often referred to as the "sticky bit".

-rwxr-xr-x 1 root root 41368 2010-04-12 14:03 more
-rwsr-xr-x 1 root root 72952 2010-04-12 14:03 mount
-rwxr-xr-x 1 root root 9800 2010-04-26 05:02 mountpoint

Why don't you describe what you are really trying to acomplish and maybe I can provide a better solution.

If you are just trying to change to the other user in the script then drop sudo from and it will work.

This article has been dead for over six months. Start a new discussion instead.