bash – How to assign output/error to a variable in bash

bashshell-scriptssh

I have the following line in my bash file:

LIST=$(ssh 192.168.0.22 'ls -1 /web');

The problem I am having is that it is a part of automated script and I often get this on the stdout and not the data I need:

ssh_exchange_identification: Connection closed by remote host

I realize that LIST only gets the stdout of the ls. So I am looking for a command that would get more of the info from the commands. In particular:

  • stdout for ls – I have that right now
  • stderr for ls – not really interested, I don't expect a problem there
  • stdout for ssh – Not interested, I don't even know what it would output
  • stderr for sshTHIS IS WHAT I AM LOOKING FOR to check whether it ssh correctly. This being empty should mean that I have the data in $LIST I expect

Best Answer

From ssh man page on Ubuntu 16.04 (LTS):

EXIT STATUS
     ssh exits with the exit status of the remote command or with 255 if an error occurred.

Knowing that, we can check exit status of ssh command. If exit status was 225, we know that it's an ssh error, and if it's any other non-zero value - that's ls error.

#!/bin/bash

TEST=$(ssh $USER@localhost 'ls /proc' 2>&1)

if [ $? -eq 0 ];
then
    printf "%s\n" "SSH command successful"
elif [ $? -eq 225   ]
    printf "%s\n%s" "SSH failed with following error:" "$TEST"
else 
    printf "%s\n%s" "ls command failed" "$TEST"
fi
Related Question