Search code examples
shellsh

Run .sh file terminal


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?


Solution

  • 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.