在Linux/POSIX系统上获得用户全名的最简单方法是什么? [英] What's the easiest way to get a user's full name on a Linux/POSIX system?

查看:72
本文介绍了在Linux/POSIX系统上获得用户全名的最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过/etc/passwd grep,但这似乎很麻烦.未安装"finger",我想避免这种依赖性.这是一个程序,因此如果有一些命令可以让您访问用户信息,那就太好了.

I could grep through /etc/passwd but that seems onerous. 'finger' isn't installed and I'd like to avoid that dependency. This is for a program so it would be nice if there was some command that let you just access user info.

推荐答案

您没有指定编程语言,因此我假设您要使用shell.这是 Posix shell的答案.

You don't specify a programming language, so I'll assume you want to use the shell; here's an answer for Posix shells.

执行以下两个步骤:获取适当的记录,然后从该记录中获取所需的字段.

Two steps to this: get the appropriate record, then get the field you want from that record.

首先,通过查询passwd来获取帐户记录:

First, getting the account record is done by querying the passwd table:

$ user_name=foo
$ user_record="$(getent passwd $user_name)"
$ echo "$user_record"
foo:x:1023:1025:Fred Nurk,,,:/home/foo:/bin/bash

对于歇斯底里的葡萄干,用户的全名记录在称为 "GECOS"的字段中"字段 ;使事情复杂化的是,该字段通常具有自己的结构,其中全名只是几个可选子字段之一.因此,想要从帐户记录中获取全名的任何内容都需要解析这两个级别.

For hysterical raisins, the full name of the user is recorded in a field called the "GECOS" field; to complicate matters, this field often has its own structure with the full name as just one of several optional sub-fields. So anything that wants to get the full name from the account record needs to parse both these levels.

$ user_record="$(getent passwd $user_name)"
$ user_gecos_field="$(echo "$user_record" | cut -d ':' -f 5)"
$ user_full_name="$(echo "$user_gecos_field" | cut -d ',' -f 1)"
$ echo "$user_full_name"
Fred Nurk

您的编程语言可能具有库功能,以较少的步骤完成此操作.在C语言中,您将使用"getpwnam"功能,然后解析GECOS字段.

Your programming language probably has a library function to do this in fewer steps. In C, you'd use the ‘getpwnam’ function and then parse the GECOS field.

这篇关于在Linux/POSIX系统上获得用户全名的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆