2

Imaging I am executing the following command:

echo "root:mypass" | chpasswd

How can I get the return code / error code returned by chpasswd? Is that possible in this case at all? I tried

RET = `echo "root:mypass" | chpasswd`

but this gives me only "command not found"?

  • 1
    Be aware that every string passed as an argument to a command can be read by users using ps, or other means. – Stéphane Gimenez Sep 17 '12 at 19:00
7

The $? variable holds the return value of the last command. You could do this:

echo "root:passwd" | chpasswd
RET=$?

Or test directly, e.g.

echo "root:passwd" | chpasswd
if [ "$?" -ne 0 ]; then
  echo "Failed"
fi
  • Thank you, that seems to work! Still wondering, if there is some kidn of "direct way" like in my example above? – stefan.at.wpf Sep 2 '12 at 20:29
  • No, but you can test on $? immediately afterwards without storing it in another variable if you don't need to keep it. Of course, if you run any other command it will update $? with its own result. – teppic Sep 2 '12 at 20:32
3

If the return value isn't important, just if it succeeds or no, you can use the command within an if statement:

if ! echo "root:mypass" | chpasswd; then
  # chpasswd failed
fi

Or the shorter one:

echo "root:mypass" | chpasswd || cmd_to_run_if_chpasswd_failed
0

If I understand properly you're trying to change the pass of the root user using only an statement and pressing enter with no more confirmation of the process.

I found that your statement, runs properly if you add a "sudo su" prefix.

~$ sudo su

Considering that you're trying to change the pass of the root user, you must to know what is the root user name and to be logged properly. You can do this with the sudo su command.

Then its enough with runs the follow command replacing "root" with the current root name, and "my pass" with the desired password for this user (remember to take a note for try this method):

~$ echo "root:mypass" | chpasswd

After you can probe entering a exit command and login command using the new password.

  • You are not answering the OP's question, he was looking for a way to retrieve the return code for this command. – Stéphane Gimenez Sep 17 '12 at 19:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.