如何在Bash中获得当前用户的用户名?我用whoami吗?
当前回答
我在Solaris 9和Linux上使用的一种hack,它对这两种系统都很有效:
ps -o user= -p $$ | awk '{print $1}'
这个代码段打印带有当前EUID的用户名。
注意:这里需要Bash作为解释器。
在Solaris上,您会遇到上述方法的问题:
Id不接受-u和-n参数(因此必须解析输出) Whoami不存在(默认情况下) 我是谁打印当前终端的所有者(忽略EUID) $USER变量只有在读取配置文件(例如/etc/profile)后才能正确设置。
其他回答
在命令行中输入
whoami
or
echo "$USER"
对于Bash, KornShell (ksh), sh等。你的许多问题很快就会被回答:
man [function]
要获得您正在使用或通常更方便的系统的文档:
谷歌“man函数”
对于Linux和Unix略有不同的某些事情,这可能会给出不同的结果。
对于这个问题,只需在你的shell中输入“whoami”。
编写脚本:
myvar=$(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
whoami的替代品是id - un -n。
Id -u将返回用户Id(例如root为0)。
在Solaris操作系统中,我使用了这个命令:
$ who am i # Remember to use it with space.
在Linux上——有人已经在评论中回答了这个问题。
$ whoami # Without space