So basically, I want to get a list of all users in a text file. First, I tried to ls
the /home
directory and output it to a file. But when I did this, It just put the users in a list like user1 user2 user3 user4
but I need the list like this:
user1
user2
user3
user4
So any help would be great! Thanks
CodePudding user response:
You can get a list of users directly from /etc/passwd
by simply excluding the system accounts. You need to know what the UID_MIN
and UID_MAX
for your distribution. You can get that simply with, e.g.
$ grep '^UID_' /etc/login.defs
UID_MIN 1000
UID_MAX 60000
Now simply output the users from /etc/passwd
(and optionally sort) excluding UIDs outside that range, e.g.
$ awk -F: '$3 >= 1000 && $3 <= 60000 { print $1 }' /etc/passwd | sort
alan
anna
darrell
david
deborah
dell
dmimms
drr
...
To save to a file, simply redirect the result to a filename of your choosing, e.g.
$ awk -F: '$3 >= 1000 && $3 <= 60000 { print $1 }' /etc/passwd | sort > filename
CodePudding user response:
you can try ls > filename.txt
CodePudding user response:
With bash's globbing (*
):
cd /home/
printf "%s\n" * >file
Output to file:
user1 user2 user3 user4
See: help printf
CodePudding user response:
suggesting to use find
command.
find /home -maxdepth 1 -mindepth 1 -type d -printf "%f\n"
Or better inspect those users who have a valid shell.
Not all users that have a shell have a home directory.
awk -F: '/nologin$/{next}{print $1}' /etc/passwd