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.

I have a bash script that calls an expect script.

The expect script has several conditions. It ssh's into a box and executes a command, and there are different possible errors that could happen which I have given exit codes like so:

expect {
    "passwd: password updated successfully" {
    exit 0
    }
    "Password unchanged" {
    exit 1
    }
    "Bad: new and old password are too similar" {
    exit 2
    }
    "You must choose a longer password" {
    exit 3
    }
}

I had planned to take those exit codes and use them in the bash script that called the expect script, like so:

            if [ $? -eq 0 ]; then
            echo -e "\n"
            echo "Password successfully changed on $host by $user"

            elif [ $? -eq 1 ]; then
                echo "Failure, password unchanged"
            elif [ $? -eq 2 ]; then
                echo "Failure, new and old passwords are too similar"
            elif [ $? -eq 3 ]; then
                echo "Failure, password must be longer"
            else
                echo "Password failed to change on $host"
        fi

But that doesn't work. It seems that the expect script only returns 0 if it succeeds or 1 if it fails, regardless of where it fails. Is it possible to retrieve the exit codes I assign and use them in the bash script?

Or would it be better to use "send_user" in the expect script to describe the error? If so, how would I be able to have the bash script use the output of the "send_user" command in expect?

share|improve this question

2 Answers 2

A simpler way would be to use a case statement instead of checking $? repeatedly:

case "$?" in
    0) echo "Password successfully changed on $host by $user" ;;
    1) echo "Failure, password unchanged" ;;
    2) echo "Failure, new and old passwords are too similar" ;;
    3) echo "Failure, password must be longer" ;;
    *) echo "Password failed to change on $host" ;;
esac
share|improve this answer

You need to initialize return value to a temporary variable. so like this:

   ./my_expect_script.expect
   a=$?
   if [ $a -eq 0 ]; then
        echo -e "\n"
        echo "Password successfully changed on $host by $user"

        elif [ $a -eq 1 ]; then
            echo "Failure, password unchanged"
        elif [ $a -eq 2 ]; then
            echo "Failure, new and old passwords are too similar"
        elif [ $a -eq 3 ]; then
            echo "Failure, password must be longer"
        else
            echo "Password failed to change on $host"
    fi
share|improve this answer

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.