Short, simple command to create a group if it doesn't already exist?

22,573

Solution 1

getent group somegroupname || groupadd somegroupname

Solution 2

With force it exits successfully if the group already exists, and cancels -g if the GID is already used.

groupadd -f somegroupname
Share:
22,573

Related videos on Youtube

Oleg
Author by

Oleg

Updated on September 18, 2022

Comments

  • Oleg
    Oleg almost 2 years

    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.

  • Oleg
    Oleg almost 10 years
    Thanks. In case it helps anyone, this slight modification avoids printing output from the first command: [ $(getent group somegroupname) ] || groupadd somegroupname
  • Angel Todorov
    Angel Todorov almost 10 years
    Or just redirect it's output to /dev/null