如何获取执行Perl脚本的用户的名称?

时间:2021-04-22 07:16:14

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运行它时,我可以很容易地使用由$ bash提供的$ ENV {“USER”}。

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上运行。

4 个解决方案

#1


9  

crontab sets $LOGNAME so you can use $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.

crontab设置$ LOGNAME,因此您可以使用$ ENV {“LOGNAME”}。默认情况下,我的环境中也设置了$ LOGNAME(虽然没有看到它设置的位置),因此您可能只能使用$ LOGNAME而不是$ USER。

Although I agree with hacker, don't know what's wrong about getpwuid.

虽然我同意黑客,但不知道getpwuid有什么问题。

#2


46  

Try getting your answer from several places, first one wins:

尝试从几个地方获得答案,首先获胜:

my $username = $ENV{LOGNAME} || $ENV{USER} || getpwuid($<);

#3


8  

Does this look prettier?

这看起来更漂亮吗?

use English qw( −no_match_vars );

my $username = getpwuid $UID;

#4


2  

Sorry, why doesn't that "look nice"? That's the appropriate system call to use. If you're wanting an external program to invoke (e.g. 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可供使用。

#1


9  

crontab sets $LOGNAME so you can use $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.

crontab设置$ LOGNAME,因此您可以使用$ ENV {“LOGNAME”}。默认情况下,我的环境中也设置了$ LOGNAME(虽然没有看到它设置的位置),因此您可能只能使用$ LOGNAME而不是$ USER。

Although I agree with hacker, don't know what's wrong about getpwuid.

虽然我同意黑客,但不知道getpwuid有什么问题。

#2


46  

Try getting your answer from several places, first one wins:

尝试从几个地方获得答案,首先获胜:

my $username = $ENV{LOGNAME} || $ENV{USER} || getpwuid($<);

#3


8  

Does this look prettier?

这看起来更漂亮吗?

use English qw( −no_match_vars );

my $username = getpwuid $UID;

#4


2  

Sorry, why doesn't that "look nice"? That's the appropriate system call to use. If you're wanting an external program to invoke (e.g. 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可供使用。