Reputation: 193
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.
Upvotes: 1
Views: 364
Reputation: 19555
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.
Upvotes: 3
Reputation: 42999
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:
Upvotes: 2