1

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?

2 Answers 2

4

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
3

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .