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

Viewed 52611

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.

5 Answers

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.

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.

Also, I'm surprised no one mentioned getlogin(), though that doesn't always work. For best chance of actually getting the username, I suggest:

my $username = getlogin() || (getpwuid($<))[0] || $ENV{LOGNAME} || $ENV{USER};
Related