sftp return code

17,680

You need to run sftp in batch mode, by putting your commands in a file and passing that to sftp. You will then get an exit code of 1 if there is a failure and 0 for success.

Here is some sample code:

# create a temporary file containing sftp commands
BATCH_FILE="/tmp/$(basename $0).$$.tmp"
echo ${cmdPut} > ${BATCH_FILE}
echo ${cmdRen} >> ${BATCH_FILE}

# run sftp in batch mode
sftp -b ${BATCH_FILE} ${sftpOption} ${targetUsername}@${targetHostname} 
sftpStatus=$?

rm ${BATCH_FILE}
Share:
17,680
Prasanna Diwadkar
Author by

Prasanna Diwadkar

Updated on June 04, 2022

Comments

  • Prasanna Diwadkar
    Prasanna Diwadkar about 1 year

    I seacrhed the site for this problem but could not find solution.Problem is related to sftp.I am running a script which accepets 7 parameters,does SSH and uploads the file on sftp server.Parameters i supply are-server,user,port,source_directory,target_directory,source_file and tager_file. if everything goes fine, file is uploaded without any error and return code is 0. Problem is if any parameter is wrong, like target_directory, even then script returns 0 as return value.Here is how script looks-

       typeset targetUsername=$1
    
    typeset targetHostname=$2
    
    typeset sftpPort=$3
    
    typeset sourceDir=$4
    
    typeset targetDir=$5
    
    typeset sourceFilename=$6
    
    typeset targetFilename=$7
    
    typeset cmdPut="put ${sourceDir}/${sourceFilename} ${targetTempDir}/${tmpFileNam
    e}"
    
    typeset cmdRen="rename ${targetTempDir}/${tmpFileName} ${targetDir}/${targetFile
    name}"
    
    sftp ${sftpOption} ${targetUsername}@${targetHostname} <<EOF
    
    ${cmdPut}
    
    ${cmdRen}
    
    bye
    EOF
    
    sftpStatus=$?
    

    sftpStatus is supposed to return the status.But i am getting status as 0 always. Any idea, how to resove this? Thanks alot in advance.

  • Prasanna Diwadkar
    Prasanna Diwadkar about 12 years
    Thanks alot. I will try soon and put the result here.
  • Prasanna Diwadkar
    Prasanna Diwadkar about 12 years
    Hi,i m getting error in renaming the file."No such file or directory"
  • dogbane
    dogbane about 12 years
    are you sure the targetDir exists?
  • Prasanna Diwadkar
    Prasanna Diwadkar about 12 years
    oops.there was problem with directory.Its working fine now.thanks
  • user3761541
    user3761541 over 4 years
    Thank you, so much for this solution. It worked for me as well.