尝试找出Linux脚本

尝试找出Linux脚本

我是一个相当新的 Linux 用户,我正在尝试为课程编写一个脚本。

该脚本应该允许用户输入用户名,并且它会说明该用户名是否存在。如果存在,则输出其 UID 和主目录,如果不存在,则输出“此用户不存在”。

到目前为止,这是我的脚本:

#!/bin/bash

echo "Type in the username you'd like to lookup. Type quit to quit."
read username
    if grep -c $username /etc/passwd; then
            echo "The user '$username' exists! Posting information..."
        id -u $username
        eval echo $USER
    else
            echo "Sorry... I couldn't find the user '$username'."
    fi

我目前正试图弄清楚一些事情:

我怎样才能让输入 quit 实际上退出脚本?实际上是echo $HOST发布所输入的用户名的主目录,还是只是放置当前用户的主目录?我在系统上创建了一些额外的帐户来测试脚本,但主目录每次都是相同的。

示例输出:

mamurphy@ubuntu:~$ ./user_lookup
Type in the username you'd like to lookup. Type quit to quit.
mamurphy
1
The user 'mamurphy' exists! Posting information...
1000
/home/mamurphy

mamurphy@ubuntu:~$ ./user_lookup
Type in the username you'd like to lookup. Type quit to quit.
moemam
2
The user 'moemam' exists! Posting information...
1001
/home/mamurphy

mamurphy@ubuntu:~$ ./user_lookup
Type in the username you'd like to lookup. Type quit to quit.
bob
0
Sorry... I couldn't find the user 'bob'.

答案1

$HOME你的主目录,而不是您输入的用户的主目录。您需要查找它:

user=moemam
user_home=$(getent passwd "$user" | cut -d: -f6)

答案2

我怎样才能让输入 quit 实际上退出脚本?

这是一个非常基本示例:

#!/bin/bash

echo "Type in the username you'd like to lookup. Type quit to quit."
read answer
if [[ "$answer" == "quit" ]]; then
    exit 1
fi

if grep -q "$answer" /etc/passwd; then
        id -u "$answer"
else
    echo "User $answer not found"
    exit 2
fi

exit 0

测试:

./readAns.sh 
Type in the username you'd like to lookup. Type quit to quit.
quit
echo $?
1
./readAns.sh 
Type in the username you'd like to lookup. Type quit to quit.
ntp
119
echo $?
0
./readAns.sh 
Type in the username you'd like to lookup. Type quit to quit.
foo
User foo not found
echo $?
2

相关内容