How can I retrieve an entry from /etc/passwd for a given username?

后端 未结 1 761
后悔当初
后悔当初 2020-12-12 08:03

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 informatio

相关标签:
1条回答
  • 2020-12-12 08:27

    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
    

    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
    

    This way is very efficient, it set a global variable without forks.

    0 讨论(0)
提交回复
热议问题