如何在Bash中获得当前用户的用户名?我用whoami吗?
当前回答
两个命令:
Id打印用户Id和组。 格式:uid=usernumber(用户名)… Whoami给出当前用户名
其他回答
当前用户的用户名可以在纯Bash中通过${parameter@operator}参数展开(在Bash 4.4中引入)获得:
$ : \\u
$ printf '%s\n' "${_@P}"
内置(true的同义词)通过设置最后一个参数来代替临时变量,该参数存储在$_中。然后我们展开它(\u),就好像它是一个带有P操作符的提示字符串。
这比使用$USER更好,因为$USER只是一个常规的环境变量;它可以被修改、取消设置等。即使它没有被故意篡改,一种常见的情况是,当用户在没有启动登录shell (su的默认)的情况下切换时,它仍然是不正确的。
whoami的替代品是id - un -n。
Id -u将返回用户Id(例如root为0)。
这是一个小的简单示例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
获取当前任务的user_struct
#define get_current_user() \
({ \
struct user_struct *__u; \
const struct cred *__cred; \
__cred = current_cred(); \
__u = get_uid(__cred->user); \
__u; \
})
在Solaris操作系统中,我使用了这个命令:
$ who am i # Remember to use it with space.
在Linux上——有人已经在评论中回答了这个问题。
$ whoami # Without space