I already have an ssh agent set up, and I can run commands on an external server in Bash script doing stuff like:
ssh blah_server "ls; pwd;"
Now, what I'd really like to do is run a lot of long commands on an external server. Enclosing all of these in between quotation marks would be quite ugly, and I'd really rather avoid ssh'ing multiple times just to avoid this.
So, is there a way I can do this in one go enclosed in parentheses or something? I'm looking for something along the lines of:
ssh blah_server (
ls some_folder;
./someaction.sh;
pwd;
)
Basically, I'll be happy with any solution as long as it's clean.
Edit
To clarify, I'm talking about this being part of a larger bash script. Other people might need to deal with the script down the line, so I'd like to keep it clean. I don't want to have a bash script with one line that looks like:
ssh blah_server "ls some_folder; ./someaction.sh 'some params'; pwd; ./some_other_action 'other params';"
because it is extremely ugly and difficult to read.
This can also be done as follows. Put your commands in a script, let's name it commands-inc.sh
Save the file
Now run it on the remote server.
Never failed for me.
The posted answers using multiline strings and multiple bash scripts did not work for me.
Here is a functional way to ssh and run multiple commands while keeping local context.
Put all the commands on to a script and it can be run like
For anyone stumbling over here like me - I had success with escaping the semicolon and the newline:
First step: the semicolon. This way, we do not break the ssh command:
Listed the remote hosts /home directory (logged in as root), whereas
listed the current working directory.
Next step: breaking up the line:
This again listed the remote working directory - improved formatting:
If really nicer than here document or quotes around broken lines - well, not me to decide...
(Using bash, Ubuntu 14.04 LTS.)
I see two ways:
First you make a control socket like this:
and run your commands
This way you can write an ssh command without actually reconnecting to the server.
The second would be to dynamically generate the script,
scp
ing it and running.SSH and Run Multiple Commands in Bash.
Separate commands with semicolons within a string, passed to echo, all piped into the ssh command. For example: