0

I ran below command line from a terminal and it works:

sftp -i ~/.ssh/id_rsa username@host
put csv_file
put manifest_file

I want to automatically run this so I created a .sh file that looks like below:

#!/bin/bash
sftp -i ~/.ssh/id_rsa username@host
put csv_file
put manifest_file

and save it as run.sh. I ran it like below:

sh run.sh 

It connect to the host but the next commands, the put lines, did not run.

Can I get insights why is that and how can I solve it?

chandra sutrisno
  • 491
  • 4
  • 17
  • Don't use `sh` to run Bash scripts. (Your script doesn't contain any Bash-specific syntax, so in this case, it doesn't matter, but you need to understand the difference.) – tripleee Jan 12 '23 at 08:04
  • Your code should not "not run", but should stall on the `sftp` command, because sftp expects its commands (`put` and so on) from standard input. – user1934428 Jan 12 '23 at 08:10

1 Answers1

3

It worked interactively because put commands were not consumed by shell but running sftp process. Script you have attempts to run put commands as standalone.

Redirection

To run put you can either feed them to standard input of the sftp:

#!/bin/bash
sftp -i ~/.ssh/id_rsa username@host <<END
put csv_file
put manifest_file
END

where <<END denotes take next lines until seeing END and redirect them (<<) to the standard input of sftp.

Batch File

Or alternatively if you can automate them via batch file called e.g. batch and containing simply the put lines:

put csv_file
put manifest_file

and then tell sftp it should process commands in batch file like this instead of having shell script:

sftp -i ~/.ssh/id_rsa username@host -b batch

NOTE: Since you have bash shebang in file you can make that file executable by chmod +x run.sh and then simply run it as ./run.sh.

blami
  • 6,588
  • 2
  • 23
  • 31