Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

perl

People also ask

How do I print a script name in Perl?

use File::Basename; my $name = basename($0);

What is Getpwuid in Perl?

Description. This function returns a list of fields in list context, as extracted from the /etc/passwd file, based on the user name specified by EXPR. It.s generally used like this − ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwuid ($uid); In a scalar context, returns the user name.


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

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

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.


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 (e.g. something you could use from a bash script too), there are the tools /usr/bin/id and /usr/bin/whoami for use.