tags:

views:

308

answers:

4

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  A: 

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.

Vinko Vrsalovic
+2  A: 

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.

Andy Ross
+5  A: 

Does this look prettier?

use English qw( −no_match_vars );

my $username = getpwuid $UID;
Chas. Owens
Heh. In my actual code, I (of course) use English, and I actually use $REAL_USER_ID, but I didn't want to spark any "English vs. Short-names" debate in here :)
depesz
In my code I would use `$<`, so that isn't a debate I care about, but I thought you might consider it prettier.
Chas. Owens
+4  A: 

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

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