Add a user to the system *only if it doesn't exist*

id -u somename returns a non-zero exit code when the user does not exist.

You can test it quite simply... (&>/dev/null just supresses the normal output/warning)

id -u somename &>/dev/null || useradd somename 

try this:

useradd {user} || echo "User already exists."

or even this:

useradd {user} || true

Unless you only have a small handful of systems, you are asking the wrong question. The answer is not to run useradd at all, but instead leave this work to a configuration management solution like puppet or chef. This will allow your user definitions to be centralized and prevent you from running for loops and using ssh with root users in order to configure your systems. You will always have systems in a known configuration state.

Documentation for puppet is available at http://docs.puppetlabs.com

As an example in puppet:

user { "bob" : 
  password   => "$1$yv3n066X$Vpb05Ac/fHTicNdT9T5vz1", # generated with `openssl passwd -1`
  ensure     => present,                              # ensure => absent to remove
  managehome => true,
}

Tags:

Users