How to get exit code of spawned process?

  • Dmm

    Dmm - 2010-11-24

    For example, we we ssh to run some commands remotely, and they fails with exit code 22 and with no stdout/stderr:

    spawn -noecho ssh -C "$user@$host" $cmds
    expect {
        -re ".*es.*o.*" {
            exp_send "yes\r"
        -re ".*sword.*" {
            exp_send "$password\r"
    # ??? How to get ssh exit code here ???


  • Dmm

    Dmm - 2010-11-24

    s/we we ssh/we use ssh/

  • ender

    ender - 2010-11-26

    If the problem is that spawning ssh fails then you can catch errors from spawn like this

    if [catch "spawn ssh" reason] {
    send_user "failed to spawn program: $reason\n"
    exit 1

    That is from the book exploring expect.

    If it is actually spawning ssh properly and then ssh runs but can't connect or something else, then try expecting the error message.

  • Dmm

    Dmm - 2010-11-26

    There is no error message, ssh can silently die with non-null exit code. There also is another problem with running remote process via spawn. If I use catch+wait, expect hangs in 10-15 seconds and is not able to finish, even with Ctrl+C. I able to see spawned in ps aux, it runs and exiits successfully, but expect is completely hanged up.

  • ender

    ender - 2010-11-30

    Can you expect eof and deal with it that way?

  • ender

    ender - 2010-11-30

    From looking in the book again there is a sample script that gets the exit value by spawning a shell and then running the command you need the value from. It uses the shells command to get the exit value, $? or $status in the script.

  • SpiderErrol

    SpiderErrol - 2013-07-30

    This is probably 3 years too late for you, but might help someone searching with a similar problem. After the "interact", add the following code:

    # This will wait for ssh to exit (if it hasn't already), and capture it's exit value.
    set waitval [wait -i $spawn_id]
    set exval [lindex $waitval 3]
    # $exval contains the value from ssh, so do something interesting with it or just return it to your own caller:
    exit $exval

    This was tested with expect version 5.45


Log in to post a comment.