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
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
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.