Question

I am writing a SH-script that downloads a file from an SFTP server. I want to recognize if any error appears during the SFTP connection of my script. But without redirecting my outputs and neither using grep because I already redirect my outputs to different log files.

I try to make a command similar to the below example but I need the {---?---} parts. I use a case syntax for example, but I can use if, or any other syntaxes.

sftp <user>@<host>:<remote_file> <local_destination>

if [ $? != 0 ];
    then
        case {---?---} in
            {---?---})
                _error_exit "permission denied, please try again"
                ;;
            {---?---})
                _error_exit "SFTP server not responding, maybe offline"
                ;;
            {---?---})
                _error_exit "file not found"
                ;;
            *)
                _error_exit "unable to download the file from SFTP server"
        esac
    else
        _status "file downloaded"
    fi
}
Was it helpful?

Solution

The OpenSSH sftp command has only two exit codes, 0 for success and 1 for failure.

So if you need to distinguish different errors, parsing the command output is your only way.

You can redirect sftp command output to a temporary file, parse the temp file to find an error message and then print the temp file to output, so that it is included into your log too.

sftp ... > /tmp/sftp.log
grep ... /tmp/sftp.log
...
cat /tmp/sftp.log
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top