如何在Bash中获得当前用户的用户名?我用whoami吗?
当前回答
两个命令:
Id打印用户Id和组。 格式:uid=usernumber(用户名)… Whoami给出当前用户名
其他回答
这是一个小的简单示例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)。
在大多数Linux系统上,只需在命令行上键入whoami即可提供用户ID。
但是,在Solaris上,您可能必须通过下面的命令确定登录用户的UID来确定用户ID。
echo $UID
一旦知道了UID,就可以通过与/etc/passwd文件匹配UID来查找用户。
cat /etc/passwd | cut -d":" -f1,3
两个命令:
Id打印用户Id和组。 格式:uid=usernumber(用户名)… Whoami给出当前用户名