[英]How can I get name of the user executing my Perl script?
I have a script that needs to know what username it is run from.我有一个脚本需要知道它是从哪个用户名运行的。
When I run it from shell, I can easily use $ENV{"USER"}, which is provided by bash.当我从 shell 运行它时,我可以轻松使用 $ENV{"USER"},它由 bash 提供。
But apparently - then the same script is run from cron, also via bash - $ENV{"USER"} is not defined.但显然 - 然后从 cron 运行相同的脚本,也通过 bash - $ENV{"USER"} 未定义。
Of course, I can:当然,我可以:
my $username = getpwuid( $< );
But it doesn't look nice - is there any better/nicer way?但它看起来不太好 - 有没有更好/更好的方法? It doesn't have to be system-independent, as the script is for my personal use, and will be only run on Linux.它不必与系统无关,因为该脚本仅供我个人使用,并且只能在 Linux 上运行。
尝试从几个地方获得答案,首先获胜:
my $username = $ENV{LOGNAME} || $ENV{USER} || getpwuid($<);
crontab sets $LOGNAME
so you can use $ENV{"LOGNAME"}
. crontab设置$LOGNAME
因此您可以使用$ENV{"LOGNAME"}
。 $LOGNAME
is also set in my environment by default (haven't looked where it gets set though) so you might be able to use only $LOGNAME
instead of $USER
. 默认情况下,我的环境中也设置了$LOGNAME
(虽然没看过它设置的位置),所以你可能只能使用$LOGNAME
而不是$USER
。
Although I agree with hacker, don't know what's wrong about getpwuid
. 虽然我同意黑客,但不知道getpwuid
什么问题。
Does this look prettier? 这看起来更漂亮吗?
use English qw( −no_match_vars );
my $username = getpwuid $UID;
Sorry, why doesn't that "look nice"? 对不起,为什么不“看起来不错”? That's the appropriate system call to use. 这是适当的系统调用。 If you're wanting an external program to invoke (eg something you could use from a bash script too), there are the tools /usr/bin/id and /usr/bin/whoami for use. 如果你想要一个外部程序来调用(例如你可以从bash脚本中使用的东西),还有工具/ usr / bin / id和/ usr / bin / whoami可供使用。
Apparently much has changed in Perl in recent years, because some of the answers given here do not work for fetching a clean version of "current username" in modern Perl.显然,近年来 Perl 发生了很大变化,因为这里给出的一些答案不适用于在现代 Perl 中获取“当前用户名”的干净版本。
For example, getpwuid($<) prints a whole bunch of stuff (as a list in list context, or pasted-together as a string in scalar context), not just the username, so you have to use (getpwuid($<))[0] instead if you want a clean version of the username.例如, getpwuid($<) 打印一大堆东西(作为列表上下文中的列表,或作为标量上下文中的字符串粘贴在一起),而不仅仅是用户名,因此您必须使用 (getpwuid($<) )[0] 如果你想要一个干净的用户名版本。
Also, I'm surprised no one mentioned getlogin(), though that doesn't always work.另外,我很惊讶没有人提到 getlogin(),尽管这并不总是有效。 For best chance of actually getting the username, I suggest:为了获得实际获得用户名的最佳机会,我建议:
my $username = getlogin() || (getpwuid($<))[0] || $ENV{LOGNAME} || $ENV{USER};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.