I would like to create a script that:
- run some commands
- execute sudo su - [some other username]
- after I exit from [some other username] -> logout
Example: test.sh
echo "test script"
sudo su
logout
If I run a script like this:
echo "test"
sudo su
whomai
I get the wanted result:
[wolfy@ubuntusrv ~ ]# ./test.sh
test
[root@ubuntusrv wolfy]# date
Fri 19 Jun 10:56:52 CEST 2015
[root@ubuntusrv wolfy]# echo bla
bla
[root@ubuntusrv wolfy]# exit
wolfy
[wolfy@ubuntusrv ~ ]#
As you can see, the script runs my echo command and then I sudo su to root, where I can do what I need to do and after I quit root session the script execute the last (whoami) command.
My problem is that I can't logout myself at the end of this script.
I need a way to do this without root privileges.
Can someone help me?
Additional explanation:
- when I run sudo su - username (userA) I need to provide my password (wolfy) to login as the other user (userA). Then I work for the whole session with that user (userA) and when I logout from that user (userA) I would like to automatic logout from my (wofly) user.
- using sudo command is not an option
Perhaps all you want to do is:
This replaces your current shell process by the script, so that when it finishes there is nothing left to run.
Typically, to run a command as root,
sudo
is sufficient.If you insist on using
su
,for whatever reason, you can use -c flag :And here's the result, same in both cases:
If you want to enter root shell, use
sudo -i
With su :
If you want to run commands as another user, not only root, you can use
sudo -u username command
Same idea with
su
:A
logout
in a script doesn't affect anything, sincelogout
only works for login shells, and scripts aren't typically run as login shells.It seems to me that you're logging on via SSH (or something), running as another user and immediately logging out. In that case, just source the script, so that the commands are run in your current shell. Then,
logout
will work.Or, you can use
exec
, but in that case, it isn'tlogout
that's taking effect -logout
will fail, and the end of the script simply causes it to exit. Distinction without a difference, I suppose.Or, if you find it cumbersome to use
. ./script
, define a function with braces:Commands in braces run in the current shell, and commands in parentheses are run in a sub-shell. Add this to your
.bashrc
, then you can simply do: