0

I have the following code in a function. Is there a way to get the exit code after the expect script is run, however do a command with the exit code within the same function? I know you can you "$?" after the function is executed, however I would like to handle the exit code accordingly within the function itself.

getVersion(){
cmd="command_with_options"
mcasPassword="sample"
expect <<-EOS |& tee ${hostname}.log
        #!/usr/bin/expect
        set timeout $EXP_TIMEOUT
        spawn sh
        expect "$prompt"
        send -- "$cmd\r"
        expect "*assword"
        send -- "$mcasPassword\r"
        expect {
                "*rror*" {
                puts "\nAn issue was faced\n"
                exit 1
                }
                "$prompt" {
                puts "\nSuccessfully reached\n"
                }
        }
        expect eof
        exit 0
EOS
echo "Error code is as follows: $?"
#The above line isn't capturing the exit code ^
}

Any help would be highly appreciated.

Shak
  • 103
  • 8
  • https://unix.stackexchange.com/questions/14270/get-exit-status-of-process-thats-piped-to-another https://stackoverflow.com/questions/1221833/pipe-output-and-capture-exit-status-in-bash https://stackoverflow.com/questions/32684119/exit-when-one-process-in-pipe-fails – KamilCuk Apr 26 '21 at 07:18
  • Hi @KamilCuk , I'm unsure as to how the attached questions answer within a expect script context. Could you please explain or provide an example? – Shak Apr 26 '21 at 07:37
  • `echo "Error code is as follows: ${PIPESTATUS[0]}"` – KamilCuk Apr 26 '21 at 07:41
  • You can store the exit code on a global var before exiting and access it to exit from the script. – samthegolden Apr 26 '21 at 10:05

1 Answers1

0

Thank you @KamilCuk for posting the answer to this question:

echo "Error code is as follows: ${PIPESTATUS[0]}"
Shak
  • 103
  • 8