Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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"?

share|improve this question
    
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
add comment

3 Answers

up vote 7 down vote accepted

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
share|improve this answer
    
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
    
Thanks, accepted as correct answer ;-) –  stefan.at.wpf Sep 2 '12 at 20:48
add comment

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
share|improve this answer
add comment

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.

share|improve this answer
    
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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