jkshah
jkshah

Reputation: 11703

Extract user name from perl script

I want to extract user name, executing a perl script, within a script itself.

I am executing whoami linux command from perl as follows and it works pretty well.

my $whoami = `whoami`;
chomp $whoami;
print $whoami;

My intention is to get away from calling system commands from perl script. Therefore I am looking for Perl only solution. I was wondering if there is any CPAN module available which can extract system information.

Your suggestions in this regards will be appreciated.

Upvotes: 4

Views: 5473

Answers (3)

edi_allen
edi_allen

Reputation: 1872

You should probably take at look at the hash %ENV. It contains useful information about the environment where your script is run.

One example (in windows) to get the username would be:

perl -E "say $ENV{'USERNAME'}"

For bash substitute USERNAME for either LOGNAME or USER.

Upvotes: 3

Oleg V. Volkov
Oleg V. Volkov

Reputation: 22421

Perl have direct mapping to system getpw* functions.

These routines are the same as their counterparts in the system C library. In list context, the return values from the various get routines are as follows:

($name,$passwd,$uid,$gid, $quota,$comment,$gcos,$dir,$shell,$expire) = getpw*

-- from perldoc -f getpwuid.

Use getpwuid with $< as argument (which, according to perldoc perlvar is "The real uid of this process", and also available as $REAL_USER_ID and $UID) and get first returned value.

Upvotes: 3

Grrrr
Grrrr

Reputation: 2536

perl -le 'print scalar getpwuid $<'

Upvotes: 9

Related Questions