Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sftp return code

Tags:

sftp

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.

like image 703
Prasanna Diwadkar Avatar asked Feb 24 '23 12:02

Prasanna Diwadkar


1 Answers

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}
like image 131
dogbane Avatar answered Mar 20 '23 23:03

dogbane