Ssh run multiple commands in one line

In most of the cases we run ssh to execute one command or script on remote machine ,actually we can run multiple commands in one line with ssh.
Use ; to run multiple commands in sequence
Here ; means no matter the previous command run successfully or failed, the next command always will be executed.
ssh host "cmd1;cmd2;cmd3"
And the background is : initialize a ssh session with server host , by default without tty (notty) , the execute command in remote host.
bash -c"cmd1;cmd2;cmd3"
Use && to run multiple commands
Here && means only the previous command run successfully then the next command will be executed.
ssh host "cmd1 && cmd2 && cmd3"
Only cmd1 succeeded then cmd2 will be executed , similarly only if cmd2 succeeded then cmd3 will be executed.
For example:
j@ubuntu:~$ ssh 192.168.171.161 "touch /root/abc ; echo done"
touch: cannot touch '/root/abc': Permission denied
done
j@ubuntu:~$ ssh 192.168.171.161 "touch /root/abc && echo done"
touch: cannot touch '/root/abc': Permission denied
j@ubuntu:~$
Here we can see while using ; , although command touch /root/abc failed , command echo done still been executed.
But while using && , because the first command failed ,so echo done was not been executed.
Use || to run multiple commands
Here || means only if the previous command failed then the next command will be executed.
ssh host "cmd1 || cmd2 || cmd3"
Let’s also see an example:
j@ubuntu:~$ ssh 192.168.171.161 "touch /root/abc >/dev/null 2>&1 || echo failed"
failed
Here because the first command touch /root/abc failed then echo failed been executed.
>/dev/null 2>&1 means redirect both standard output and standard error to null.
Multiple lines
In case you need to run many commands or you think one line command is a little bit ugly , you can try below
ssh hosts "
cmd1
cmd2
cmd3
"
Or with && and ||
ssh host "
cmd1 &&
cmd2 ||
cmd3
"
Some shells like csh doesn’t support newlines between double quotes , you can use below method instead
ssh hosts <<EOF
cmd1
cmd2
EOF