Home » Linux » How can I get name of the user executing my Perl script?

How can I get name of the user executing my Perl script?

Posted by: admin November 30, 2017 Leave a comment

Questions:

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.

But apparently – then the same script is run from cron, also via bash – $ENV{“USER”} is not defined.

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.

Answers:

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.

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

Questions:
Answers:

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

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

Questions:
Answers:

Does this look prettier?

use English qw( −no_match_vars );

my $username = getpwuid $UID;

Questions:
Answers:

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.