Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question

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
share|improve this answer
<<< was introduced first by zsh (though inspired by rc) and was later added to ksh93 and then bash. – Stéphane Chazelas Nov 8 '12 at 22:34
Thank you, @StephaneChazelas. I really need to strengthen my zsh skills. – manatwork Nov 9 '12 at 8:49
+1 Worked great, thank you. – Hazok Sep 8 '14 at 18:34

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

 printf '%s\n' 'lcd /home' 'cd /myhome' 'get file' | sftp -b - user@host
share|improve this answer
To use variables change ' to " – Radnaskela Samot Nov 9 '12 at 8:43

Yes, you can just use echo -e

echo -e "lcd /home\ncd /myhome\nget file" | sftp user@host
share|improve this answer
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 '12 at 16:59

Use native sftp command

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

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.