id(1) can handle uid arguments

This commit is contained in:
Rob Pilling 2013-12-01 11:40:49 +00:00 committed by sin
parent fd8c3b6438
commit d453be2ae1
2 changed files with 39 additions and 18 deletions

6
id.1
View File

@ -3,10 +3,10 @@
id \- print real and effective user and group IDs id \- print real and effective user and group IDs
.SH SYNOPSIS .SH SYNOPSIS
.B id .B id
.RB [ user ] .RB [ user | uid ]
.SH DESCRIPTION .SH DESCRIPTION
Print user and group information of the calling process to standard output. Print user and group information of the calling process to standard output.
If a login name is specified, the user and group information of that user If a login name or uid is specified, the user and group information of that
is displayed. user is displayed.
.SH SEE ALSO .SH SEE ALSO
.IR who(1) .IR who(1)

51
id.c
View File

@ -7,21 +7,22 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <limits.h> #include <limits.h>
#include <ctype.h>
#include "util.h" #include "util.h"
static void user(struct passwd *pw); static void user(struct passwd *pw);
static void userid(uid_t id);
static void usernam(const char *nam);
static void static void
usage(void) usage(void)
{ {
eprintf("usage: %s [user]\n", argv0); eprintf("usage: %s [user | uid]\n", argv0);
} }
int int
main(int argc, char *argv[]) main(int argc, char *argv[])
{ {
struct passwd *pw;
ARGBEGIN { ARGBEGIN {
default: default:
usage(); usage();
@ -30,20 +31,14 @@ main(int argc, char *argv[])
errno = 0; errno = 0;
switch (argc) { switch (argc) {
case 0: case 0:
pw = getpwuid(getuid()); userid(getuid());
if (errno != 0)
eprintf("getpwuid %d:", getuid());
else if (!pw)
eprintf("getpwuid %d: no such user\n", getuid());
user(pw);
break; break;
case 1: case 1:
pw = getpwnam(argv[0]); /* user names can't begin [0-9] */
if (errno != 0) if (isdigit(argv[0][0]))
eprintf("getpwnam %s:", argv[0]); userid(estrtol(argv[0], 0));
else if (!pw) else
eprintf("getpwnam %s: no such user\n", argv[0]); usernam(argv[0]);
user(pw);
break; break;
default: default:
usage(); usage();
@ -52,6 +47,32 @@ main(int argc, char *argv[])
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }
static void usernam(const char *nam)
{
struct passwd *pw;
errno = 0;
pw = getpwnam(nam);
if (errno != 0)
eprintf("getpwnam %s:", nam);
else if (!pw)
eprintf("getpwnam %s: no such user\n", nam);
user(pw);
}
static void userid(uid_t id)
{
struct passwd *pw;
errno = 0;
pw = getpwuid(id);
if (errno != 0)
eprintf("getpwuid %d:", id);
else if (!pw)
eprintf("getpwuid %d: no such user\n", id);
user(pw);
}
static void static void
user(struct passwd *pw) user(struct passwd *pw)
{ {