Identify user in a Bash script called by sudo

前端 未结 7 2109
闹比i
闹比i 2020-12-07 14:39

If I create the script /root/bin/whoami.sh containing:

#!/bin/bash
whoami

and this script is called by a user with a properly

7条回答
  •  我在风中等你
    2020-12-07 15:01

    $SUDO_USER doesn't work if you are using sudo su -.
    It also requires multiple checks - if $USER == 'root' then get $SUDO_USER.

    Instead of the command whoami use who am i. This runs the who command filtered for the current session. It gives you more info than you need. So, do this to get just the user:

    who am i | awk '{print $1}'
    

    Alternatively (and simpler) you can use logname. It does the same thing as the above statement.

    This gives you the username that logged in to the session.

    These work regardless of sudo or sudo su [whatever]. It also works regardless of how many times su and sudo are called.

提交回复
热议问题