Solved Problem assigning command output to variable

Solved issue

banderas20

Active Member
Joined
Aug 1, 2018
Messages
115
Reaction score
47
Credits
917
Hi!

I'm writing a shellscript to check whether a server is reachable via SSH.

I assign the SSH command output to a shell variable so I can tell if it works or not.
I also limit the time with the timeout command. So my script looks like this:

OUTPUT=$(timeout 60s ssh user@server)

Possible expected values of "OUTPUT":

  • empty string -> time runs out and "timeout" cancels the SSH command.
  • "user@server's password:" -> the server answers and prompts for password.
  • "ssh: connect to server port 22: Connection timed out" -> the system exceeds the timeout and I receive this specific error.

I have a problem with the value of the variable.

From the prompt, ssh user@server succeeds in less than one minute, giving the expected output.
timeout 60s ssh user@server also gives the expected result.

But If I run the script, OUTPUT variable is always empty. As if the server was always unreachable.
The same happens If I run from the prompt: OUTPUT=$(timeout 60s ssh user@server). echo $OUTPUT shows nothing.

Maybe it has something to do with the assignation to the variable?

Thanks for the help!
 


To summarize a little bit:
Code:
localuser@debian:~/Documents$ ssh user@server
ssh: connect to host server port 22: Connection timed out

localuser@debian:~/Documents$ OUTPUT=$(ssh user@server)
ssh: connect to host server port 22: Connection timed out
localuser@debian:~/Documents$ echo $OUTPUT

"OUTPUT" holds nothing...
 
"user@server's password:" -> the server answers and prompts for password.
In this case the ssh process is not finished, so as I think you can't save this output to a variable yet. You may have to use Expect or something.
Bash:
man expect
 
with output=$(ssh user@server 2>&1) I was able to capture the error.

Also, if the timeout command runs, the SSH command is cancelled with no string at all.
 
with output=$(ssh user@server 2>&1) I was able to capture the error.

Also, if the timeout command runs, the SSH command is cancelled with no string at all.
This is what came to mind when I saw the post. An error is normally printed to stderr instead of stdout and I didn't know if $(cmd) would print both of them together. I'm glad things worked for you. Thank you for sharing your solution so the rest of us can learn from your troubles.

Signed,

Matthew Campbell
 

Members online


Top