Bash 将输出/错误分配给变量

Pat*_*uch 5 bash ssh shell-script

我的 bash 文件中有以下行:

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

我遇到的问题是它是自动化脚本的一部分,我经常在stdout我需要的数据上而不是在我需要的数据上得到它:

ssh_exchange_identification: Connection closed by remote host

我认识到,LIST只有得到stdoutls。所以我正在寻找一个可以从命令中获取更多信息的命令。特别是:

  • stdout因为ls- 我现在有那个
  • stderr因为ls- 不是很感兴趣,我不希望那里有问题
  • stdoutfor ssh- 不感兴趣,我什至不知道它会输出什么
  • stderrfor ssh-这就是我要检查它ssh是否正确。这是空的应该意味着我有$LIST我期望的数据

Ser*_*nyy 9

从 Ubuntu 16.04 (LTS) 上的 ssh 手册页:

EXIT STATUS
     ssh exits with the exit status of the remote command or with 255 if an error occurred.
Run Code Online (Sandbox Code Playgroud)

知道了这一点,我们可以检查ssh命令的退出状态。如果退出状态是225,我们知道这是一个ssh错误,如果它是任何其他非零值 - 那就是ls错误。

EXIT STATUS
     ssh exits with the exit status of the remote command or with 255 if an error occurred.
Run Code Online (Sandbox Code Playgroud)