The following command sends one command to sftp using one line:

sftp -o PasswordAuthentication=no user@host" <<<"lcd /home"

How to send multiple lines to sftp using one line. Is there a way to insert carriage returns or something to achieve this, for example:

sftp -o PasswordAuthentication=no user@host" <<<"lcd /home\n cd /myhome\n get file"

The idea is to NOT use the sftp -b option where an external file listing commands is loaded.

6 Answers 6


From the here-string (<<<) syntax you used I guess your shell is bash, so you can also use string with backslash-escaped characters ($''):

sftp -o PasswordAuthentication=no user@host <<< $'lcd /home\n cd /myhome\n get file'

The portable alternative is here-document:

sftp -o PasswordAuthentication=no user@host <<END
lcd /home
cd /myhome
get file
  • 1
    <<< was introduced first by zsh (though inspired by rc) and was later added to ksh93 and then bash. Nov 8, 2012 at 22:34
  • Thank you, @StephaneChazelas. I really need to strengthen my zsh skills.
    – manatwork
    Nov 9, 2012 at 8:49

Use the -b/--batchfile option to have proper error handling:

 printf '%s\n' 'lcd /home' 'cd /myhome' 'get file' | sftp -b - user@host

Yes, you can just use echo -e

echo -e "lcd /home\ncd /myhome\nget file" | sftp user@host
  • 4
    echo is very non-standard - echo -e doesn't work the same everywhere, so you'd have to check first. Alternatively, just use printf which is much more portable and should work the same everywhere.
    – jw013
    Nov 8, 2012 at 16:59

It is not necessary to avoid the -b option to avoid writing the batch file to disk. Using process substitution you can create the batch on the fly.

batch() {
  echo lcd /home
  echo cd /myhome
  echo get file

sftp -b <(batch) -o PasswordAuthentication=no user@host

Mybru, you can mos pipe your commands like so:

echo '
    lcd /home
    cd /myhome
    get file
' | sftp -o PasswordAuthentication=no user@host

Use native sftp command

sftp -o PasswordAuthentication=no user@host:/home/myhome/file

  • What you didn't notice was that lcd and cd do different things. You've just combined the paths into something that will not exist. Aug 14, 2018 at 13:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .