72

I've been running the useradd {user} command to add users to my system, though I plan on running this in an automated environment, and it might end up being run again, even though the user already exists.

Is there a way that I can run this only if the user doesn't already exist? The user doesn't have a home folder.

dr_
  • 29,602
tarnfeld
  • 831

4 Answers4

99

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 
Peter.O
  • 32,916
27

try this:

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

or even this:

useradd {user} || true
sebaszw
  • 331
8

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,
}
Aaron Brown
  • 1,245
  • 9
    Puppet is a great project, but you cannot make assumptions about what the OP is really asking :) – rahmu Mar 24 '12 at 15:20
  • 1
    The OP explained the goal very clearly - automated and able to be run again even though the user exists (idempotency). These are the exact use cases for a configuration management tool. When someone isn't aware that tools already exist to solve these problems, they tend to ask questions that involve solving a very specific, narrowly focused problem when there is a larger concept to grasp. – Aaron Brown Mar 24 '12 at 16:29
  • I'm already using Chef. – tarnfeld Jun 06 '13 at 09:50
  • 2
    Chef will only add users if the user doesn't exist. That's what idempotency is, so I don't understand the question (1.5 years out now). – Aaron Brown Jun 06 '13 at 13:06
5

useradd would not add the user again if it exists already, it intends to make sure the uid number and uid login are unique. If you are planning to run through a batch, make sure the uids being used are unique; useradd would complain for the problematic entries and you need to capture the errors/stderr to see which user accounts had problems getting into the account systems (/etc/passwd, group, shadow).

Yuri
  • 458