How to execute a multiline command using ssh on a remote Linux machine?

Viewed 50

My local machine has Windows OS. My remote machine has Linux OS. I'm trying to run some bash commands on the remote machine from my local machine (with the use of ssh). In the powershell script below I'm feeding a multiline comment to stdin input of ssh client. The code does not work and gives me an error. The problem is that each line passed to bash has \r (carriage return symbol) appended to it and bash interprets it as a part of a command. What are my options here?

Powershell script

ssh -tt "$Username@$Host" @"
    cd /home/someuser/project
    cd ~
"@

Bash error

bash: line 0: cd: $'/home/someuser/project\r': No such file or directory
1 Answers

I assume you execute ssh from Windows PowerShell or PowerShell Core on Windows as it is using CRLF for line breaks. bash doesn't like CRLF. So, concatenate your commands with line delimiters and pass it to ssh in one line:

ssh -tt "$Username@$Host" "cd /home/someuser/project; cd ~"

If it is a larger script, you can maintain it in a file an convert it automatically to a (not really) "one-liner":

$myBashScript = (Get-Content 'my-bash-script.txt') -join ';'
ssh -tt "$Username@$Host" $myBashScript
Related