Philip J.
Philip J.

Reputation: 33

How can I return an error in bash expect?

I have a bash expect script like this, that I use for some operations on Jamf:

spawn firmwarepasswd -setpasswd 
expect { 
    "Enter password:" { 
        send "$oldpass\r" 
        exp_continue 
    }
    "Enter new password:" { 
        send "$newpass\r" 
        exp_continue
    } 
    "Re-enter new password:" { 
    send "$newpass\r"
    exp_continue
    }
}

If the password fails, the script will not exit and jamf will keep trying to execute it. How can I get it to return and exit when the password is wrong?

Upvotes: 2

Views: 249

Answers (1)

Bayou
Bayou

Reputation: 3441

I don't know Jamf, but I do have a little example for you:

function _cmd {
        local cmd="${@?No command?}"
        echo -ne "Testing $cmd\t: "
        expect 2>&1 <<-EOF
                set timeout -1
                spawn ${cmd}
                expect eof
                catch wait result
                exit [lindex \$result 3]
EOF     
        echo $?
}

function _ssh {
        local status="${@?No command?}"
        read -sp "remote password? " remote_pass
        echo -ne "\nTesting ssh\t: "
        expect 2>&1 <<-EOF
                set timeout -1
                spawn ssh [email protected]
                expect {
                        "yes/no" { send "yes\r"; exp_continue }
                        "*password: " { send "${remote_pass}\r" }
                }
                expect "*#" { send "exit $status\r" }
                expect eof
                catch wait result
                exit [lindex \$result 3]
EOF
echo $?
}

_cmd false
_cmd true
_ssh 3

exit 0

The last part after expect eof makes sure that the exit status is shared. The _ssh command will exit with status 3.

Upvotes: 1

Related Questions