0

I have a script which contains the following:

sftp $2@$3 <<< $"cd $4 \nput $5 \nbye"

which I pass variables too at runtime however, the \n characters are not rendered as new lines but are rendered as plaintext so the commands attempts to to the following:

sftp > cd $4\nput $5 \nbye

which is obviously a directory which doesn't exist, how can i make the new line characters persist?

if i dont parameterise the command it works fine eg.

sftp user@host <<< $'cd dir\n put file\n bye'

any ideas?

Maybe is due the the user of ' vs " in the script?

Chris Edwards
  • 1,518
  • 2
  • 13
  • 23
  • 1
    `$"..."` is used for translatable strings; there is no equivalent to `$'...'` that allows for parameter expansion. – chepner Oct 02 '15 at 19:38
  • You can use `printf '%s\n' "cd $4" "put $5" "bye" | stfp $2@$3` or `stfp $2@$3 < <(printf '%s\n' "cd $4" "put $5" "bye")`. – gniourf_gniourf Oct 05 '15 at 08:52

2 Answers2

3

You could use a HERE document to achieve mimicking interactive input:

#!/bin/bash

sftp $2@$3 << EOI
cd $4
put $5
bye
EOI

See http://tldp.org/LDP/abs/html/here-docs.html for examples, and Using variables inside a bash heredoc for a gotcha.

Community
  • 1
  • 1
Raad
  • 4,540
  • 2
  • 24
  • 41
  • He doesn't *need* to use a here document, but it's certainly more readable (and portable) than cramming multiple lines into a single here string. – chepner Oct 02 '15 at 19:37
  • @chepner - heh, absolutely, no need - it was just one possible solution. For some reason I _needed_ to use the word _need_ - perhaps I was feeling _needy_... – Raad Oct 05 '15 at 08:56
2

Maybe is due the the user of ' vs " in the script?

Yes, that seems to be the case:

$ cat <<< $'foo\nbar'
foo
bar

but

$ cat <<< $"foo\nbar"
foo\nbar

I'm not sure what <<< and $'...' do in bash, but for your application, you should consider using a 'HERE document' like mentioned in another answer.

Community
  • 1
  • 1
das-g
  • 9,718
  • 4
  • 38
  • 80