Search code examples
linuxbashshellauthenticationsu

Execute command if I logged in from a specific user


I have a server that has a superuser (user1) with special rights to perform certain operations. And there are some other system users.

Is there any way to execute set of commands if and only if I logged in from system user (user2)?

Or any way to identify from which system user I have logged in to my superuser?

For example, I want to run a script which will, if I login from system user (user2), execute:

[user2@test ~]$ sudo su - user1
user2 Password:
[user1@test ~]$ sh script.sh

Solution

  • The who am i command will show the name of the user that originally logged in on that terminal. You can use that to detect if you've switched from one user account to another with su. So in ~user1/.profile you can put:

    orig_user=$(who am i | awk '{print $1}')
    if [[ $orig_user = user2 ]]
    then
        sh script.sh
    fi