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.
In Linux, the /etc/passwd file stores the user information, such as the user's name, UID, group id (GID), user's home directory, and user's shell. We can get the username by parsing the /etc/passwd file.
-G, --groups: It is used to print all group Ids. -n, --name: It is used to print a name instead of a number. -r, --real: It is used to print the real ID instead of the effective ID, with -ugG. -u, --user: It is used to print only the effective UID.
How to get Username from UID in Linux. Although, there is no built in command get fetch the username from the UID. We can use a pipe and regular expression match on getent to do that. getent is a unix command that helps a user get entries in a number of important text files called databases.
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
.
Simply use the id command
id username
[root@my01 ~]# id sylvain
uid=1003(sylvain) gid=1005(sylvain) groups=1005(sylvain)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With