http://qs321.pair.com?node_id=1214768


in reply to use getpwent to find users and delete them

garcimo:

The documentation (perldoc -f getpwent) indicates that getpwent returns a list of values like:

my ( $name, $passwd, $uid, $gid, $qutoa, $comment, $gcos, $dir, $shell +, $expire ) = getpwent;

and, if the user doesn't exist, it returns a "single meaningless true value". So I'd suggest calling getpwent, and then checking one of the values after the first one to see if it's defined or not. If not, the user ought not exist. So something like:

my ( $name, $passwd, $uid, $gid, $qutoa, $comment, $gcos, $dir, $shell +, $expire ) = getpwent($account); # An account *must* have a UID, so let's check that if ( defined $uid ) { print "User $account uid=$uid. OK to delete user!\n"; } else { print "User $account does not exist...\n"; }

...roboticus

When your only tool is a hammer, all problems look like your thumb.

Replies are listed 'Best First'.
Re^2: use getpwent to find users and delete them
by garcimo (Novice) on May 18, 2018 at 13:48 UTC
    Hello sadly it does not work. executing this:
    #!/usr/bin/perl use warnings; use strict; my $account = "tata"; my ( $name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell +, $expire ) = getpwent($account); if ( defined $uid ) { print "User $account uid=$uid. OK to delete user!\n"; } else { print "User $account does not exist...\n"; }
    gives me errors:

    syntax error at ./users_detect.pl line 9, near "($account" Execution of ./users_detect.pl aborted due to compilation errors.

    if I do not put the getpwent($account) it compiles but always returns uid=0 whatever the account

      I think getpwent expects no parameter. It's unfortunate that it (or Perl) doesn't say so...

      Changing your code to use getpwnam instead works for me:

      my ( $uid ) = getpwnam($account);

      garcimo:

      Sorry about that, I thought that I tested that, but it's obvious that I didn't. (Generally, I try to test my assumptions before converting a preview into an actual post, but it appears I made a mistake this time!)

      Good thing that Corion++ noticed the error and showed you the appropriate fix.

      ...roboticus

      When your only tool is a hammer, all problems look like your thumb.