quit 才結束。用 id $1 判斷用戶是否存在(成功返回 0),用 id -u 取 UID,再從 /etc/passwd 中截取第七段得到 Shell。外層用無限 while 循環維持交互。
#!/bin/bash
#Author: MOS
#Script name: funUinfo.sh
#Version: 1.0.1
# 定義函數
Find_u(){
# 參數為空則結束,返回 1
[ -z "$1" ] && return 1
# 用戶存在則輸出信息,否則返回 1
if id "$1" &> /dev/null ; then
echo "$1 UID is `id -u $1`"
echo "$1 Shell is `grep "^$1:" /etc/passwd | cut -d':' -f7`"
else
return 1
fi
}
# 循環執行以滿足題目要求
while :; do
read -p "Please input A username[quit to exit]: " User
if [ "$User" = quit ]; then
exit 0
else
Find_u "$User"
Res=$?
[ $Res -eq 1 ] && echo "No such $User."
fi
done
變量引用一律加引號,這能避免用戶名為空或含空格時測試語句報錯;while : 是 Shell 中最簡潔的無限循環寫法,等價於 while true。