Search code examples
bashshellerror-handlingshopenssh

How to Catch an Error While Establishing Remote Connection in Shell Script


This is how part of my shell script looks like.

#! /bin/sh
sftp -i $IdentityFile $ServerAddress << EOF
command 1 #Execute in the remote
command 2 #Execute in the remote
bye
EOF
command 3 #Execute locally

As per my current knowledge of scripting, if a command fails to execute, the control simply passes to the next command. But what if the sftp command fails to establish a network connection in the above block? Does it mean command 1 and command 2 will be executed locally? Or will the control jump to command 3?

How do I catch a possible error in sftp and direct the control to command 3? And if that is possible, can I detect the error using the ? variable, to take certain pre-emptive action? Some guidance will be great.


Solution

  • There are several things to do.

    First, you need to extract the input as a function, to allow piping with command3, and it will be more legible:

    function sfpInstruction() {
    cat << EOF
    command 1
    command 2
    bye
    EOF
    }
    

    Thus, your sftp instruction can be changed to:

    tmpFile="/tmp/errorFile.txt"
    sftp -i $IdentityFile $ServerAddress $( sfpInstruction ) 2>"$tmpFile" || command3
    

    Such a way:

    • all error messages are outpu in your error file
    • in any case, if sftp exits with a failing status (NOT 0), GNU/Bash will execute command3
    • if in addition you want command3 to read/check/parse the error messages, you can give it the "$tmpFile"