问题描述
如果我创建的脚本/root/bin/whoami.sh
包含:
If I create the script /root/bin/whoami.sh
containing:
#!/bin/bash
whoami
此脚本由具有正确配置的sudo的用户调用,它将指示
and this script is called by a user with a properly configured sudo, it will indicate
root
是否有一种快速的方法来获取脚本中的实际用户,还是我不得不求助于该用户名传递的参数?
Is there a fast way to obtain the actual user in a script, or will I have to resort to parameters passing along this username?
推荐答案
$ SUDO_USER在使用sudo su -
时不起作用.
它还需要进行多次检查-如果$USER == 'root'
然后得到$SUDO_USER
.
$SUDO_USER doesn't work if you are using sudo su -
.
It also requires multiple checks - if $USER == 'root'
then get $SUDO_USER
.
使用who am i
代替命令whoami
.这将运行针对当前会话过滤的who
命令.它为您提供了比您所需更多的信息.因此,执行此操作仅获得用户:
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}'
或者(更简单),您可以使用logname
.它与上述声明具有相同的作用.
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.
这些工作与sudo
或sudo su [whatever]
无关.无论调用su
和sudo
多少次,它也都起作用.
These work regardless of sudo
or sudo su [whatever]
. It also works regardless of how many times su
and sudo
are called.
这篇关于在sudo调用的Bash脚本中标识用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!