dnickel has asked for the wisdom of the Perl Monks concerning the following question:

I am writing a script to add users. I need to come up with a routine that parse's the passwd or group file and gets the next available userid. Can anyone help me? I am running FREEBSD

Replies are listed 'Best First'.
Re: Getting Next Available Userid
by merlyn (Sage) on Sep 19, 2001 at 19:30 UTC
Re: Getting Next Available Userid
by nardo (Friar) on Sep 19, 2001 at 19:09 UTC
    You can use getpwent to get all of the uid's from /etc/passwd then find a free one, or alternately you could run through uid's with getpwuid until you find a free one. Both of these suffer from the fact that a free uid is not necessarily free once you have found it (since another process could have added it right after you found it was free). I assume that programs like useradd will lock the /etc/passwd to prevent this situation, but they may use fcntl for file locking as it is more portable than flock (you can build perl to emulate flock with fcntl(2), but by default it will use flock(2) if available). For groups it would be the same, with getgrent and getgrgid.
Slightly OT: Why? Re: Getting Next Available Userid
by xphase_work (Pilgrim) on Sep 19, 2001 at 19:13 UTC
    Just out of curiosity, why are you writing a script to do this? FreeBSD's adduser program works very well for this. I'm not sure, but I think that you can use it non-interactively as well.

    --xPhase

Re: Getting Next Available Userid
by traveler (Parson) on Sep 19, 2001 at 19:16 UTC
    This partially depends on what "available" means. If it means the next highest uid, try Unix::PasswdFile. It has a method to find the highest UID. An example in the POD even shows how to add a user with the next highest uid.

    HTH, --traveler