Execute command in sftp connection through script

You can change your script to pass commands in a here-document, e.g.,

#!/bin/bash

sftp -oPort=23 [email protected]:/home/kalenpw/TestWorld/plugins <<EOF
put /home/kalenpw/.m2/repository/com/Khalidor/TestPlugin/0.0.1-SNAPSHOT/TestPlugin-0.0.1-SNAPSHOT.jar   
exit
EOF

The << marker followed by the name (EOF) tells the script to pass the following lines until the name is found at the beginning of the line (by itself).


You might prefer to use scp instead of sftp. scp behaves much like the ordinary cp command does, but the files can be remote:

scp -P 23 /home/kalenpw/.m2/repository/com/Khalidor/TestPlugin/0.0.1-SNAPSHOT/TestPlugin-0.0.1-SNAPSHOT.jar [email protected]:/home/kalenpw/TestWorld/plugins

This copies the file on you local machine into a directory on the remote machine without having to use the old-school ftp-style command interface.

The ssh, scp, and sftp services are usually available if any of them are; the same daemon program provides all of them simultaneously. In principle the server's administrator could choose to disable any of them, but in practice that's quite rare.


You can also use the -b option of sftp to indicate a file containing commands for sftp.

For example, you can put all your commands in file sftp_commands.txt:

cd /home/kalenpw/TestWorld/plugins
put /home/kalenpw/.m2/repository/com/Khalidor/TestPlugin/0.0.1-SNAPSHOT/TestPlugin-0.0.1-SNAPSHOT.jar
exit

and run sftp as:

sftp -oPort=23 -b sftp_commands.txt [email protected]:/home/kalenpw/TestWorld/plugins 

Or you can pass the commands via STDIN too if you don't want to use a file.

From man sftp:

-b batchfile

Batch mode reads a series of commands from an input batchfile instead of stdin. Since it lacks user interaction it should be used in conjunction with non-interactive authentication. A batchfile of ‘-’ may be used to indicate standard input. sftp will abort if any of the following commands fail: get, put, reget, rename, ln, rm, mkdir, chdir, ls, lchdir, chmod, chown, chgrp, lpwd, df, symlink, and lmkdir. Termination on error can be suppressed on a command by command basis by pre‐ fixing the command with a ‘-’ character (for example, -rm /tmp/blah*).