9

In linux, If I only have the user name, how to get the user id? I used man getuid, but can't find any clues about it. EDIT1: Sorry , I want to get the user id by api. I don't like forking a another process to do it such as calling system function.

jaslip
  • 315
  • 3
  • 10

3 Answers3

14

You can use getpwnam to get a pointer to a struct passwd structure, which has pw_uid member. Example program:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <pwd.h>

int main(int argc, char *argv[])
{
    const char *name = "root";
    struct passwd *p;
    if (argc > 1) {
        name = argv[1];
    }
    if ((p = getpwnam(name)) == NULL) {
        perror(name);
        return EXIT_FAILURE;
    }
    printf("%d\n", (int) p->pw_uid);
    return EXIT_SUCCESS;
}

If you want a re-entrant function, look into getpwnam_r.

Alok Singhal
  • 88,099
  • 18
  • 124
  • 155
4

Simply use the id command

id username

[root@my01 ~]# id sylvain
uid=1003(sylvain) gid=1005(sylvain) groups=1005(sylvain)
Sylwit
  • 1,393
  • 1
  • 10
  • 18
2

All usernames are listed in /etc/passwd, so you may grep and cut:

grep username /etc/passwd | cut -f3 -d':'
Sergey
  • 7,777
  • 4
  • 42
  • 76