Counting number of users in a group - Linux

Here is a small command to find number of users in particular group on a *nix system. An example for wheel group:


grep wheel /etc/group | fgrep -o , | wc -m

Now here's a catch, this command actually counts the commas in the line from the group file. So if there are 5 users in the group, the output will be 4. You will have to add a 1 to the output.

So when using it in scripts, one can use it like this:


VAR1=$(($(grep wheel /etc/group | fgrep -o , | wc -m) + 1))
echo $VAR1
5

Explanation:

First grep will print only the group and its members. The members are seperated by a comma. Next we print the commas using -o option and later count them using wc command. The second example will just add a 1 to it.

Let me know if you have a better idea for the same!

Comments

Popular Posts