1

I am on an AWS instance and have need to make a list of all the usernames on this instance. Something simple like:

ls /home > users.txt

would suffice, but I then need to go through each name and check its PID number, from there if the user doesn't have a PID number (ie a non zero return value) then I would like to delete it from the users text file i created.

I have tried the following, but received many errors:

#!/bin/bash

ls /home > users_inc.txt
while read line
do
    id -u $line
    if [$? -e 0]
    then
        echo $line > users.txt
    fi
done < users_inc.txt

Fairly new to bash scripting, any help would be appreciated.

Jay Wehrman
  • 173
  • 7
  • 1
    Do you main UID (user ID) and not PID (process ID)? If you already know which UIDs you want to delete, why bother with this loop? – jordanm Jan 27 '20 at 22:35

2 Answers2

3

Alternate method using awk:

getent passwd|awk 'BEGIN{FS=":"}{if(match($6,"/home/"$1)&&$3>=1000)print$1}'
  • getent passwd: Stream accounts records database

  • awk 'awk script': Execute awk script to parse accounts records

The awk script:

BEGIN{
  FS=":"
}
{
  if (match($6, "/home/"$1) && $3>=1000)
    print $1
}
  • BEGIN{}: Awk Initialization block executed once for the whole input stream.

    • FS=":": Define : as the Field Separator
  • {}: Main code block executed for each line or record of the input stream.

    • if (match($6, "/home/"$1) && $3>=1000): If field #6 witch is the home directory path matches /home/username (field #1) && and field #3 UID >= greater-than or equals to 1000 (minimum UID for normal accounts)

    • print $1: Then print the User Name from field #1.

Léa Gris
  • 10,780
  • 3
  • 21
  • 32
2

Modified your script, fixing the issues:

cd /home || { printf '%s\n' "Can't cd to /home" >&2; exit 1; }
for user in *; do
    if id -u "$user" >/dev/null 2>&1; then
        printf '%s\n' "$user"
    fi
done > /path/to/users.txt

Assumed that you meant ID and not PID.

Related:

codeforester
  • 28,846
  • 11
  • 78
  • 104
  • 1
    thank you for your very detailed answer. i made some edits to my original code and was able to get that to work instead, it just fit better with what i am trying to do. – Jay Wehrman Jan 27 '20 at 23:45