1

How do I write a bash shell script that requests the user's name, verify that it exists and, if it does, show the following information:

Username: xxxx
User ID: xxxx
Group ID: xxxx
Shell: / bin / xxx
Directory: / home / xxx

I have this so far:

#!/bin/bash

echo "Ingrese el nombre del usuario"
read nombreUsuario
id $nombreUsuario

RESULTADO="$?"

if [ $RESULTADO = "0" ];then
    id $nombreUsuario | tee salida.txt
    echo "id del usuario:"
    cut -f 1-1 -d" "--output-delimiter="; " salida.txt
    #asignar la salida de cut a una variable
    UID=$(cut -f 1-1 -d" " --output-delimiter="; " salida.txt)
    clear
    echo "ID del Usuario: $UID"

    #quitar el texto UID
    UIDUNICO=$(echo UID | cut -d= -f2)
    echo "ID del Usuario: $UIDUNICO"
fi

But that just shows the first part. How do I show the rest?

3
  • 1
    That's what the finger and id commands are for.
    – muru
    May 12, 2015 at 0:24
  • 3
    Don't use uppercase variable names for internal purposes. You risk overriding special shell variables and environment variables. And that just happened in your script there. UID is a special, read-only, shell variable that holds your uid. Any attempt to assign anything to UID will fail.
    – geirha
    May 12, 2015 at 7:36
  • This can be done with awk in like couple of lines. May 12, 2015 at 13:38

4 Answers 4

1

Here's one way to get the gid, uid, shell and directory:

printf "Enter username: "
read user

groupid=$( id -g $user )
userid=$( id -u $user ) 
usershell=$( grep $user /etc/passwd | awk -F':' '{ print $7 }' ) 
userdirectory=$( grep $user /etc/passwd | awk -F':' '{ print $6 }' ) 
3
  • Enclose search term inside backslash and feed the file to awk directly instead of piping from grep May 12, 2015 at 14:00
  • why at copy in the archive in nano appears syntax error?
    – alex
    May 13, 2015 at 3:25
  • That's strange, what version of bash are you using? (do this command -> "bash --version | head -1"). Also try to type in it manullay instead of copying, there becomes often problems when you copy and paste the code from a website.
    – krt
    May 13, 2015 at 5:26
0

Here is a python solution:

#!/usr/bin/env python2
import sys
with open('/etc/passwd') as f:
    for line in f:
        if line.startswith(sys.argv[1] + ':'):
            parts = line.rstrip().split(':')
            print 'Username: ' + parts[0] + '\n' + 'User ID: ' + parts[2].rstrip()
            print 'Group ID: ' + parts[3] + '\n' + 'Shell: ' + parts[6].rstrip()
            print 'Directory: ' + parts[5].rstrip()

You can put all the print statements in a single line, for better view-ability i have put it in several lines. Save this as a file e.g. username.py. Run the script giving the username as the first argument to the script. For example:

python username.py foobar

where foobar is the username.

If found the output will be like:

Username: foobar
User ID: 1000
Group ID: 1000
Shell: /bin/bash
Directory: /home/foobar
  • line.startswith(sys.argv[1] + ':') will read each line of the /etc/passwd file to check whether it begins with the given username. The : will ensure that we don't select e.g. foobarspam while our input username is foobar

  • If so, then line.split(':') will make a list of fields (separated by :) of the line

  • Then we print out the desired indexed values from the list along with the appropriate string.

0

If with "the user's" name you meant the username of the user running the script:

#!/bin/bash

read -p "Username: " username
if [ "${username}" == "${USER}" ]
then
    user_data="$(< /etc/passwd sudo grep "^${username}:")"
    echo "Username: ${username}"
    echo "User ID: $(<<<"${user_data}" cut -d: -f3)"
    echo "Group ID: $(<<<"${user_data}" cut -d: -f4)"
    echo "Shell: $(<<<"${user_data}"  cut -d: -f7)"
    echo "Directory: $(<<<"${user_data}" cut -d: -f6)"
fi

If with "the user's" name you meant any username:

#!/bin/bash

read -p "Username: " username
if [ $(< /etc/passwd grep "^$username:") ]
then
    user_data="$(< /etc/passwd sudo grep "^${username}:")"
    echo "Username: ${username}"
    echo "User ID: $(<<<"${user_data}" cut -d: -f3)"
    echo "Group ID: $(<<<"${user_data}" cut -d: -f4)"
    echo "Shell: $(<<<"${user_data}"  cut -d: -f7)"
    echo "Directory: $(<<<"${user_data}" cut -d: -f6)"
fi    
1
  • ok but when i pste this code in nano and execute with sh xxx... sintax error apear
    – alex
    May 13, 2015 at 3:24
0

Another bash way:

#! /bin/bash
read -p "Username: " user

if IFS=: details=($(getent passwd $user))
then 
    printf "Username: %s\nUser ID: %d\nGroup ID: %d\nShell: %s\nDirectory: %s\n" "${details[0]}" "${details[2]}" "${details[3]}" "${details[6]}" "${details[5]}"
fi

One can, in a single step

  • run a command, taking its output - $(getent passwd $user)
  • split the output on :, save the result as an array IFS=: details=(...)
  • and use the exit status of the command for testing in if

Then it's just a matter of printing the correct fields.

You must log in to answer this question.

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