如何在Bash中获得当前用户的用户名?我用whoami吗?
当前回答
在大多数Linux系统上,只需在命令行上键入whoami即可提供用户ID。
但是,在Solaris上,您可能必须通过下面的命令确定登录用户的UID来确定用户ID。
echo $UID
一旦知道了UID,就可以通过与/etc/passwd文件匹配UID来查找用户。
cat /etc/passwd | cut -d":" -f1,3
其他回答
All,
从我在这里看到的所有答案都是错误的,特别是如果你进入了sudo模式,所有返回'root'而不是登录用户。答案是使用'who',找到eh 'tty1'用户并提取它。“w”命令的工作原理相同,var=$SUDO_USER获得真正的登录用户。
干杯!
TBNK
在命令行中输入
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
对于Bash, KornShell (ksh), sh等。你的许多问题很快就会被回答:
man [function]
要获得您正在使用或通常更方便的系统的文档:
谷歌“man函数”
对于Linux和Unix略有不同的某些事情,这可能会给出不同的结果。
对于这个问题,只需在你的shell中输入“whoami”。
编写脚本:
myvar=$(whoami)
REALUSER="${SUDO_USER:-${USER}}"
…获取常规用户(如果不是sudo)→或←当前sudo调用背后的常规用户。