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


当前回答

在命令行中输入

whoami

or

echo "$USER"

其他回答

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

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

获取当前任务的user_struct

#define get_current_user()              \
({                                      \
    struct user_struct *__u;            \
    const struct cred *__cred;          \
    __cred = current_cred();            \
    __u = get_uid(__cred->user);        \
    __u;                                \
})

在命令行中输入

whoami

or

echo "$USER"

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

在大多数Linux系统上,只需在命令行上键入whoami即可提供用户ID。

但是,在Solaris上,您可能必须通过下面的命令确定登录用户的UID来确定用户ID。

echo $UID

一旦知道了UID,就可以通过与/etc/passwd文件匹配UID来查找用户。

cat /etc/passwd | cut -d":" -f1,3