Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

2 Answers 2

up vote 4 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 at 20:06
    
Or just redirect it's output to /dev/null –  glenn jackman Jul 18 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 at 19:52
    
you are correct. it's worked for me by accident since I had group and user names coinciding. –  George Pompidou Jul 18 at 19:58

Your Answer

 
discard

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.