I wanted to automate running a deploy script on a few servers, just by running a command from my local command line. Executing a .sh file you have on your local filesystem on a remote computer, isn’t as easy as it looks. This is how i did it.

I run this line everytime i want to execute the script on the remote server (thanks to Yves for the updated version):

cat local-script.sh | ssh user@server "sed 's/{ctrl-v}{ctrl-m}//g' | bash"

What does this do:

cat local-script.sh
This just prints the local-script.sh file to the standardoutput. This file contains the script we want to execute on the server. In our case, the contents of the file gets piped to the next segment of the line by the pipe symbol (|)

ssh user@server
This part of the script creates an ssh connection to the server. This is pretty straightforward. When that’s done, everything between the double quotes (“) gets executed on the remote host.

sed 's/{ctrl-v}{ctrl-m}//g'
This part of the script converts carriage-returns into correct unix linefeeds. This is useful when you or someone in your team is working on a Windows machine.

| bash
Finally, it’s time to run the script, so we pipe (|) it to bash (the interpreter)

That’s it 🙂