It’s very convenient to have your local user accounts sorted by uidNumber, but if you’re running the shadow suite there’s no uidNumber field in /etc/shadow to sort on. Something something something Ted Codd and the horse he rode in on.
This should work on anything with GNU sort, grep and awk and no hoary old NIS nonsense in /etc/passwd. It’s worked on every linux distro I’ve ever used, all the way back to yggdrasil, although in Ubuntu gawk is not necessarily included by default (which is weird, but easily dealt with using [insert package-manager-du-jour name here] or sudo apt-get install gawk).
touch passwd.sorted shadow.sorted
chmod 644 passwd.sorted
chmod 600 shadow.sorted
sort -t: -n -k3,3 /etc/passwd >passwd.sorted
gawk -F: '{system("grep \"^" $1 ":\" /etc/shadow")}' passwd.sorted >shadow.sorted
If you don’t trust my mad gawk skillz (or your own transcription skills) you can crudely check the results with wc, because the number of lines, words and characters will be unchanged by a clean sort.
wc /etc/shadow shadow.sorted
wc /etc/passwd passwd.sorted
cp -a /etc/passwd /root/passwd.`date -I`
cp -a /etc/shadow /root/shadow.`date -I`
mv passwd.sorted /etc/passwd && mv shadow.sorted /etc/shadow
If you’re running selinux (of course you are, my bright little star!) you need to make sure you reset the file security contexts, right quick.
restorecon -v /etc/passwd
restorecon -v /etc/shadow
Keep in mind that mucking about with primary user authentication sources is not something you should do unless you are an expert (or want to become one). And you’re going to have to be the root superuser to do this, or type “sudo” a whole lot. The consequences of error may be severe! For example, if you have selinux in enforcing mode and you reboot without resetting the security context on /etc/shadow… yeah, good luck with that.
The same procedure can be used for /etc/group and /etc/gshadow, naturlich.