Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script to switch the user

Tags:

linux

bash

I am having a cent-OS server with 5 accounts: developer, user1 ,user2 ,user3 and user4. All the user home directories are under /home like /home/developer, /home/user1, /home/user2, /home/user3 and /home/user4. I want to create a 4 scripts: user1.sh, user2.sh, user3.sh and user4.sh inside the /home/developer folder. When the user developer run the script user1.sh, he switches to the user1 and cd to the home directory of user1 (/home/user1) and so on for the remaining scripts. The idea behind is to keep the developer from the root access and allow switch to other user's home directory by simple executing a command with that user's name. Is it possible?

like image 623
Gopu Avatar asked Nov 06 '13 07:11

Gopu


People also ask

How do you switch users in shell script?

The su command lets you switch the current user to any other user. If you need to run a command as a different (non-root) user, use the –l [username] option to specify the user account. Additionally, su can also be used to change to a different shell interpreter on the fly.

How do I switch users in bash?

To change to a different user and create a session as if the other user had logged in from a command prompt, type "su -" followed by a space and the target user's username. Type the target user's password when prompted.

How do I run a script as a different user?

Running Script as Another User. By default, the su command takes an input a target username to switch into. However, we can specify a script to be run with the flag -c. When specified, su command will just execute the script without dropping into a new shell as the target user.


1 Answers

I suppose you're looking at su - otherUser

Of course, you'll have to provide the password of the other user.

I suppose that something like sudo su - otherUser could work but I haven't tried

like image 59
Bruce Avatar answered Sep 28 '22 21:09

Bruce