0

I want to write a simple Bash script which displays the path to the home directory of a user when an actual user name is used as an argument and displays user not found or something when a user name that doesn't exist on this system is used as an argument.

Would this require a function? Can this be done by using basic GNU compatible commands in a script file?

2
read -p "Enter a username: " username
if getent passwd "$username" > /dev/null
then
  printf "Their home directory is: %s\n" "$(getent passwd "$username" | cut -d: -f6)"
else
  printf "User not found!\n" >&2
fi
  • This is where i get a bit lost with BASH. I am used to powershell. are you declaring the value of $username as the content of the read-p ? In powershell it would be like: $username = read-host "enter a username" – DanMan3395 Jul 5 '18 at 17:44
  • in short, yes. the read command takes the user's input and stores it in username. – Jeff Schaller Jul 5 '18 at 17:46
  • 1
    For more information: gnu.org/software/bash/manual/html_node/… – Jeff Schaller Jul 5 '18 at 17:47
2
#!/bin/sh

username=$1

if ! getent passwd "$username" >/dev/null 2>&1; then
    printf 'User %s does not exist\n' "$username"
    exit 1
fi

homedir=$( getent passwd "$username" | cut -d: -f6 )

if [ -n "$homedir" ]; then
    if [ -d "$homedir" ]; then
        printf 'User %s has a valid (existing) home directory: %s\n' "$username" "$homedir"
    else
        printf 'User %s lacks a valid (existing) home directory: %s\n' "$username" "$homedir"
    fi
else
    printf 'User %s has no home directory\n' "$username"
fi

The script takes the username from the command line:

$ ./script.sh kk
User kk has a valid (existing) home directory: /home/kk

$ ./script.sh nobody
User nobody lacks a valid (existing) home directory: /nonexistent

$ ./script.sh aoae
User aoae does not exist
0

getent passwd <USERNAME> is a good way to read the user database. It prints the entry from the user database for the given user, if the user exists, or exits non-zero if the user doesn't exist.

So we can look at the output if it exited zero, and print an error message if it exited non-zero.

The home directory is the 6th field of the passwd entry. It can be extracted using standard text processing tools, e.g. awk or cut.

if passwd="$(getent passwd "$user")"; then
    awk -F: '{print $6}' <<<"$passwd"
else
    echo "No such user $user" >&2
fi

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.