Identify user in a Bash script called by sudo

前端 未结 7 2086
闹比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 14:52

    Here is how to get the username of the person who called the script no matter if sudo or not:

    if [ $SUDO_USER ]; then user=$SUDO_USER; else user=`whoami`; fi
    

    or a shorter version

    [ $SUDO_USER ] && user=$SUDO_USER || user=`whoami`
    

提交回复
热议问题