Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

What is the cleanest way to modify this command in bash to only run if the group does not exist?

groupadd somegroupname

A one-liner would be best.

share|improve this question
up vote 17 down vote accepted
getent group somegroupname || groupadd somegroupname
share|improve this answer
Thanks. In case it helps anyone, this slight modification avoids printing output from the first command: [ $(getent group somegroupname) ] || groupadd somegroupname – Oleg Jul 18 '14 at 20:06
Or just redirect it's output to /dev/null – glenn jackman Jul 18 '14 at 20:11
id -u somegroupname &>/dev/null || groupadd somegroupname

since id -u somegroupname will return non-zero if it doesn't exist.

share|improve this answer
I don't think this works the same everywhere. It only works for usernames on my Ubuntu 14.04 test box. – Oleg Jul 18 '14 at 19:52
you are correct. it's worked for me by accident since I had group and user names coinciding. – Georges Pompidou Jul 18 '14 at 19:58

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.