我有这个代码来生成用户帐户信息。问题是,我有一个用户名行,您将在其中键入用户名,并仅检索该指定用户名的信息。但是,代码检索系统上所有用户的信息。
#! /bin/bash
#This script returns import information about the user name on the system
echo "PLease enter name to continue:"
read SuppliedName
for user in $(cut -d: -f1 /etc/passwd)
#while [ "$SuppliedName" == "$USER" ]
do
IFS=$'\n'
userinfo=$(grep $user: /etc/passwd)
comment=$(echo $userinfo | cut -d: -f5)
home=$(echo $userinfo | cut -d: -f6)
groups=$(groups $user | cut -d: -f2)
#Skip users that do not have '/home' in the path to their home directory
if [ $(echo "$home" | grep -v '/home/') ]
then
continue
fi
echo "Username: $user"
echo "User Info: $comment"
echo "Home Directory: $home"
echo "Groups: $groups"
echo "Disk usage: $(du -sh $home)"
last=$(last $user | head -1)
if [ $( echo $last | wc -c ) -gt 1 ]
then
echo "Last login: "
echo "$last"
else
echo "User has never logged in!"
fi
echo ""
echo "--"
echo ""
done发布于 2017-11-26 04:21:30
$user和$suppliedName之间的比较,因为您在/etc/passwd上迭代以获取所有用户数据,所以可以打印出来。grep $user: /etc/passwd将对包含“$user:”的所有行进行grep,包括以该名称开头具有GECOS的用户(正确的正则表达式是^$user:)。getent。总之,我会在这方面使用finger。或将主循环重写为:
getent passwd $suppliedName | (
IFS=:
while read UNAME SHADOW UID_ GID GECOS HOME SHELL ; do
# Your code goes here
done )发布于 2017-11-26 04:45:45
你可以用另一种方式做到这一点,用更少的努力,更优雅地处理不匹配的问题。
#!/bin/bash
printf "PLease enter name to continue: " ## use printf
read -r name
info="$(grep "^$name" /etc/passwd)" ## read line into info
if [ -n "$info" ]; then ## test that info is not empty, then call awk
awk -F : '{printf "Username: %s\nUser Info: %s\nHome Directory: %s\n", $1, $5, $6 }' \
<<< "$info" ## use herestring to feed data to awk
printf "Groups: %s\n" "$(groups "$name")" ## use groups
else
printf "error: name not found '%s'\n" "$name" ## handle error/no match
fi示例使用/输出
$ bash getuser.sh
PLease enter name to continue: david
Username: david
User Info: David C. Rankin
Home Directory: /home/david
Groups: david : david adm lp sys uucp wheel vboxusershttps://stackoverflow.com/questions/47492876
复制相似问题