id: Implement -n

This commit is contained in:
tm512 2015-04-26 10:38:41 +01:00 committed by sin
parent 91cd388a39
commit d988f01f0f
2 changed files with 44 additions and 10 deletions

9
id.1
View File

@ -1,4 +1,4 @@
.Dd February 2, 2015
.Dd April 24, 2015
.Dt ID 1
.Os ubase
.Sh NAME
@ -6,9 +6,8 @@
.Nd print real and effective user and group IDs
.Sh SYNOPSIS
.Nm
.Op Fl g
.Op Fl u
.Op Fl G
.Op Fl n
.Op Fl g | u | G
.Op Ar user | uid
.Sh DESCRIPTION
.Nm
@ -17,6 +16,8 @@ If a login name or uid is specified, the user and group information of that
user is displayed.
.Sh OPTIONS
.Bl -tag -width Ds
.It Fl n
Print names instead of ID numbers, for -g, -u, and -G.
.It Fl g
Print only the effective group ID.
.It Fl u

45
id.c
View File

@ -17,12 +17,16 @@ static void user(struct passwd *pw);
static void userid(uid_t id);
static void usernam(const char *nam);
static int gflag = 0;
static int uflag = 0;
static int Gflag = 0;
static int nflag = 0;
static void
groupid(struct passwd *pw)
{
gid_t gid, groups[NGROUPS_MAX];
struct group *gr;
int ngroups;
int i;
@ -30,7 +34,13 @@ groupid(struct passwd *pw)
getgrouplist(pw->pw_name, pw->pw_gid, groups, &ngroups);
for (i = 0; i < ngroups; i++) {
gid = groups[i];
printf("%u", gid);
if (nflag) {
if (!(gr = getgrgid(gid)))
eprintf("getgrgid:");
printf("%s", gr->gr_name);
} else
printf("%u", gid);
if (i < ngroups - 1)
putchar(' ');
}
@ -45,6 +55,22 @@ user(struct passwd *pw)
int ngroups;
int i;
if (uflag) {
if (nflag)
printf("%s\n", pw->pw_name);
else
printf("%u\n", pw->pw_uid);
return;
} else if (gflag) {
if (nflag) {
if (!(gr = getgrgid(pw->pw_gid)))
eprintf("getgrgid:");
printf("%s\n", gr->gr_name);
} else
printf("%u\n", pw->pw_gid);
return;
}
printf("uid=%u(%s)", pw->pw_uid, pw->pw_name);
printf(" gid=%u", pw->pw_gid);
if (!(gr = getgrgid(pw->pw_gid)))
@ -104,7 +130,7 @@ userid(uid_t id)
static void
usage(void)
{
eprintf("usage: %s [-g] [-u] [-G] [user | uid]\n", argv0);
eprintf("usage: %s [-n] [-g | -u | -G] [user | uid]\n", argv0);
}
int
@ -112,18 +138,25 @@ main(int argc, char *argv[])
{
ARGBEGIN {
case 'g':
printf("%d\n", getegid());
return 0;
gflag = 1;
break;
case 'u':
printf("%d\n", geteuid());
return 0;
uflag = 1;
break;
case 'G':
Gflag = 1;
break;
case 'n':
nflag = 1;
break;
default:
usage();
} ARGEND;
/* ensure that only one of -g, -u, or -G was specified */
if (gflag + uflag + Gflag > 1)
usage();
switch (argc) {
case 0:
userid(getuid());