如何从/etc/passwd中检索给定用户名的条目? [英] How can I retrieve an entry from /etc/passwd for a given username?
本文介绍了如何从/etc/passwd中检索给定用户名的条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文件:/etc/passwd,我必须从该文件中选择有关作为参数传递的用户的信息(该文件包含用户和有关他们的一些信息,我必须仅选择信息和打印).
I have the file : /etc/passwd and I have to select from this file the informations about an user that is passed as an argument ( the file contains users and some informations about them and i have to select only the information and print it).
推荐答案
该问题被标记为 bash ,我可以这样做:
As this question is tagged bash, I could purpose:
getUserDetails() {
local dir gid name pass shell uid user
while IFS=':' read user pass uid gid name dir shell ;do
[ "$user" = "$1" ] &&
printf " %-14s %s\n" User "$user" UID "$uid" GID "$gid" \
"Full name" "$name" Directory "$dir" "Default shell" "$shell"
done </etc/passwd
}
getUserDetails user
User user
UID 1000
GID 1000
Full name Linux User,,,
Directory /home/user
Default shell /bin/sh
或更多 bash 面向工具的问题
or more bash tool oriented:
declare -A UserDetail
getUserDetails() {
local dir gid name pass shell uid user
while IFS=':' read user pass uid gid name dir shell ;do
[ "$user" = "$1" ] && UserDetail=( [user]=$user [name]=$name
[dir]=$dir [shell]=$shell
[UID]=$uid [GID]=$gid )
done </etc/passwd
}
getUserDetail user
printf "The full name is: %s.\n" "${UserDetail[name]}"
Linux User
declare -p UserDetail
declare -A UserDetail='([name]="Linux User,,," [user]="user" [GID]="1000" [shell]="/bin/sh" [dir]="/home/user" [UID]="1000" )'
paste <(printf "%s\n" "${!UserDetail[@]}") <(printf "%q\n" "${UserDetail[@]}")
name Linux User\,\,\,
user user
GID 1000
shell /bin/sh
dir /home/user
UID 1000
这种方法非常有效,它设置了一个 global 变量,而没有分叉.
This way is very efficient, it set a global variable without forks.
这篇关于如何从/etc/passwd中检索给定用户名的条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文