I want to create a script that asks the user for his username and check if its valid by verifying the user home directory exists. If the username exists it should send an email to the user from a predefined .txt file. If the user does not exist it should persist until a valid username is given. Also if the word "exit" is submitted as username the script should exit. This is what i have done so far:

echo "Input your username"
read username

if [$username -e $dir]
cat Message.txt | mailx -s "Subject" $username
echo "The user does not exist. Please type a valid username."

I think the part with the message is fine(not sure though) but i have problems with the exit and the input validation!

1 Answer 1


To test whether a directory exists use

if [ -d somepath ]; then ...; fi

Note the spaces around [ and ]. In your case, somepath is "$dir/$username", so the test becomes

if [ -d "$dir/$username" ]; then ...; fi

Also remember to always double-quote variable expansion, for example in the call to mailx in your code.

You can simplify the cat+mailx pipeline a bit by writing

mailx -s 'Subject' "$username" <Message.txt

Another way to test for a valid username is to run getent passwd "$username" and test its exit status:

if getent passwd "$username" >/dev/null; then
    : valid user
    : invalid user

This however does not make a difference between a service user account such as daemon and an ordinary user.

A last general comment about the script is that it possibly makes more sense to read the username from the arguments to the script, so that running the script is done with

./myscript "username"

You then use "$1" inside the script instead of "$username" (or you assign username=$1) and you don't call read to read interactively. This would make the script callable from other non-interactive scripts (possibly not useful in this instance).

This would also mean that the running the script with an invalid username would just output an error message, and the you'd just rerun the script with a new and correct name instead, getting rid of the need for doing some form of needlessly complicated input validation loop (and your exit requirement).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .