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
  • 415
  • 1
  • 4
  • 11

3 Answers3

15

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
  • 93,253
  • 21
  • 125
  • 158
5

Simply use the id command

id username

[root@my01 ~]# id sylvain
uid=1003(sylvain) gid=1005(sylvain) groups=1005(sylvain)
Sylwit
  • 1,497
  • 1
  • 11
  • 20
  • Thanks. Using `id -u sylvain` returns just the UID, which is the most convenient option in scripts. – fcorsino Oct 19 '22 at 15:22
4

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

grep username /etc/passwd | cut -f3 -d':'
Sergey
  • 7,985
  • 4
  • 48
  • 80