0

I have a loop that will connect to a server via ssh to execute a command. I want to save the output of that command.

o=$(ssh $s "$@")

This works fine. I can then do what I need with the output. However I have a lot of servers to run this against and I'm trying to speed up the process by backgrounding the ssh connection, basically to do all of the requests at once. If I wasn't saving the output I could do something like

ssh $s "$@" &

and this works fine

I haven't been able to get the correct combination to do both.

o=$(ssh $s "$@")&

This doesn't give me any output. Other combinations I've tried appear to try to execute the output. Suggestions?

Thanks!

2 Answers 2

1

A process going to the background gets its own copies of the file descriptors. The stdout (o=..) will not be available in the calling process. However, you can bind the stdout to a file and access the file.

ssh $s "$@" >outfile &
wait
o=$(cat outfile)

If you don't like files, you could also use named pipes. This way the 'wait' is done by the 'cat' command. The pipe can be reused and consumes no space on the disk.

mkfifo testpipe
ssh $s "$@" >testpipe &
o=$(cat testpipe)
Sign up to request clarification or add additional context in comments.

1 Comment

That's what I was missing. Thanks!
0

I would just use a temporary file. You can't set a variable in a background process and access it from the shell that started it.

ssh "$s" "$@" > output.txt & ssh_pid=$!

...

wait "$ssh_pid"

o=$(<output.txt)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.