Skip to content

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.

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.



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.