1

I am a fairly new Linux user and I am trying to put a script together for a class.

The script is supposed to allow a user to type in a username, and it will say if the username exists or not. If it does, output their UID and their home directory, and if not, output "This user does not exist."

This is my script so far:

#!/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

I am currently stuck on trying to figure out a few things:

How can I make it so typing quit actually quits the script? Does echo $HOST actually post the home directory for the username put in, or does it just put the current user's home directory? I have created some extra accounts on my system to test the script, but the home directory is the same every time.

Example outputs:

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 is your home directory, not the homedir of the user that you typed in. You need to look it up:

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

How can I make it so typing quit actually quits the script?

Here's a very basic example:

#!/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

Testing:

./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
  • This helped out a lot, thank you so much! +1 – Polansi Nov 17 '16 at 21:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.