如何在Bash中获得当前用户的用户名?我用whoami吗?
当前回答
使用标准的Unix/Linux/BSD/MacOS命令logname检索登录用户。这忽略了环境和sudo,因为这些都是不可靠的记者。它将始终打印登录用户的名称,然后退出。这个命令大约在1981年就出现了。
My-Mac:~ devin$ logname
devin
My-Mac:~ devin$ sudo logname
Password:
devin
My-Mac:~ devin$ sudo su -
My-Mac:~ root# logname
devin
My-Mac:~ root# echo $USER
root
其他回答
在Solaris操作系统中,我使用了这个命令:
$ who am i # Remember to use it with space.
在Linux上——有人已经在评论中回答了这个问题。
$ whoami # Without space
这是一个小的简单示例bash脚本,我把我的代码推到我的个人gitlab,它吐出我的当前用户名在我的提交消息。
# !/bin/sh
# This example script is for pushing my code to gitlab
echo Starting Push for user : $(whoami), Please enter Commit Message
below:
read varMessage
# this prompts the user for an input messsage , then saves the result in
# a variable
git add .
git commit -m "$(whoami): $varMessage"
git push -u "url_of_project" master
在我的个人gitlab中生成的提交消息如下:-
walexia : updated Matplotib example
All,
从我在这里看到的所有答案都是错误的,特别是如果你进入了sudo模式,所有返回'root'而不是登录用户。答案是使用'who',找到eh 'tty1'用户并提取它。“w”命令的工作原理相同,var=$SUDO_USER获得真正的登录用户。
干杯!
TBNK
两个命令:
Id打印用户Id和组。 格式:uid=usernumber(用户名)… Whoami给出当前用户名
获取当前任务的user_struct
#define get_current_user() \
({ \
struct user_struct *__u; \
const struct cred *__cred; \
__cred = current_cred(); \
__u = get_uid(__cred->user); \
__u; \
})