如何在Bash中获得当前用户的用户名?我用whoami吗?


当前回答

whoami的替代品是id - un -n。

Id -u将返回用户Id(例如root为0)。

其他回答

这是一个小的简单示例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

我在Solaris 9和Linux上使用的一种hack,它对这两种系统都很有效:

ps -o user= -p $$ | awk '{print $1}'

这个代码段打印带有当前EUID的用户名。

注意:这里需要Bash作为解释器。

在Solaris上,您会遇到上述方法的问题:

Id不接受-u和-n参数(因此必须解析输出) Whoami不存在(默认情况下) 我是谁打印当前终端的所有者(忽略EUID) $USER变量只有在读取配置文件(例如/etc/profile)后才能正确设置。

whoami的替代品是id - un -n。

Id -u将返回用户Id(例如root为0)。

在Solaris操作系统中,我使用了这个命令:

$ who am i     # Remember to use it with space.

在Linux上——有人已经在评论中回答了这个问题。

$ whoami       # Without space

当需要root (sudo)权限时,在使用脚本时通常是90%以上,前面答案中的方法总是将root作为答案。

获取当前“登录”用户同样简单,但需要访问不同的变量:$SUDO_UID和$SUDO_USER。

它们可以被回应:

echo $SUDO_UID
echo $SUDO_USER

或指定的,例如:

myuid=$SUDO_UID
myuname=$SUDO_USER