如何在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操作系统中,我使用了这个命令:
$ who am i # Remember to use it with space.
在Linux上——有人已经在评论中回答了这个问题。
$ whoami # Without space
REALUSER="${SUDO_USER:-${USER}}"
…获取常规用户(如果不是sudo)→或←当前sudo调用背后的常规用户。
两个命令:
Id打印用户Id和组。 格式:uid=usernumber(用户名)… Whoami给出当前用户名
我在Solaris 9和Linux上使用的一种hack,它对这两种系统都很有效:
ps -o user= -p $$ | awk '{print $1}'
这个代码段打印带有当前EUID的用户名。
注意:这里需要Bash作为解释器。
在Solaris上,您会遇到上述方法的问题:
Id不接受-u和-n参数(因此必须解析输出) Whoami不存在(默认情况下) 我是谁打印当前终端的所有者(忽略EUID) $USER变量只有在读取配置文件(例如/etc/profile)后才能正确设置。