I have a bash script that uploads a file via SFTP, with a command like this:
sshpass -pABC123 sftp user@host.com << !
cd data
put /path/file.txt
bye
!
I get an email notification from my bash script when the process is complete. I would like to capture the actual output from this command (the responses from the server or errors from sshpass) into a variable or text file and include it in my email as well.
What are my options to redirect the output. I know I can place commands into $() to capture their output, and I can use >> as well, but with the multiline input, I dont think these will work…
I have tried this:
SFTP_RESULT = (
sshpass -pABC123 sftp user@host.com << !
cd data
put /path/file.txt
bye
!
)
And I have also tried:
sshpass -pABC123 sftp user@host.com << ! >> /file.txt
and
sshpass -pABC123 sftp user@host.com >> /file.txt << !
All of these simply return back my commands which I am sending to the remote server. I dont see any of the responses from the server. When I run the script form the command line with any of the above, I see the responses on the screen.
Does anyone have any suggestions?
UPDATE
I have accepted the answer from Lars Kotthoff even though its not perfect, but based on his answer and our discussion in the comments to his answer I figured it out. This is what I did:
First I moved the sftp commands to an external file called “sftp_commands”
echo $(cat sftp_commands | sshpass -pABC123 sftp user@host.com 2>&1) >> sftp.log
For some reason that works.
Redirects work: