Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SSH Shell Script multiple commands output

Tags:

shell

ssh

I want to execute 2 commands on ssh within a shell script and retrieve the output to my local machine

example

ssh user@host "command1" > /local/1.txt

ssh user@host "command2" > /local/2.txt

I want this but with a single connection is it possible

please don't answer with "Expect" solutions...

like image 334
Killercode Avatar asked Apr 17 '26 09:04

Killercode


1 Answers

If you don't mind to use the same file for storing the output; then:

ssh user@host "command1; command2" > /local/1-2.txt

If it matters, then try something like this:

ssh user@host "command1 > /somepath/1.txt; command2 > /somepath/2.txt; ..."
scp user@host:/somepath/*.txt somelocalpath/

If you still want just a single connection, maybe this might work for you:

ssh user@host "command1; echo "this_is_a_separator"; command2" > /local/1-2.txt
sed -n '1,/this_is_a_separator/ {p}' /local/1-2.txt > /local/1.txt
sed -n '/this_is_a_separator/,$ {p}' /local/1-2.txt > /local/2.txt

The local file splitting can be done in several other ways, that was just one of them.

like image 123
hmontoliu Avatar answered Apr 19 '26 08:04

hmontoliu