Anchor(faq78)

I want to set a user's password using the Unix passwd command, but how do I script that? It doesn't read standard input!

OK, first of all, I know there are going to be some people reading this, right now, who don't even understand the question. Here, this does not work:

{ echo oldpass; echo newpass; echo newpass; } | passwd
# This DOES NOT WORK!

Nothing you can do in bash can possibly work. passwd(1) does not read from standard input. This is intentional. It is for your protection. Passwords were never intended to be put into programs, or generated by programs. They were intended to be entered only by the fingers of an actual human being, with a functional brain, and never, ever written down anywhere.

Nonetheless, we get hordes of users asking how they can circumvent 35 years of Unix security.

You have three choices. The first is to manually generate your own hashed password strings (for example, using http://wooledge.org/~greg/crypt/ or a similar tool) and then write them to your system's local password-hash file (which may be /etc/passwd, or /etc/shadow, or /etc/master.passwd, or /etc/security/passwd, or ...). This requires that you read the relevant man pages on your system, find out where the password hash goes, what formatting the file requires, and then construct code that writes it out in that format.

The second is to use [http://expect.nist.gov/ expect]. I think it even has this exact problem as one of its canonical examples.

The third is to use some system-specific tools which may or may not exist on your platform. For example, some GNU/Linux systems have a chpasswd(8) tool which can be coerced into doing these sorts of things.

A fourth option that works at least on linux (if not other systems) is  echo "password" | passwd --stdin username . Check your passwd manpage before using.

See also [:BashFAQ#faq69:FAQ #69].