如何检查ssh期间是否发生任何错误?


8

我正在编写部署脚本,如果发生任何错误,我需要回滚。

例如:

#!/bin/bash
ssh myapp '
    mkdir /some/dir
    # check if above command failed, and execute rollback script if needed
'
# or maybe do it from here?

现在,当我执行此脚本时,如果mkdir失败,它将在我的屏幕上打印并继续执行。我需要捕获该错误并对此进行处理。

Answers:


6

的退出状态ssh将是远程命令的退出状态。例如

ssh myapp 'exit 42'
echo $?

应该显示42($?是最后执行的命令的退出状态)。

一种选择是,如果mkdir失败,则立即退出:

ssh myapp 'mkdir /some/dir || exit 42; do-more-stuff'
if [[ $? = 1 ]]; then
   echo "Remote mkdir failed"
fi

如果可能的话,最好尝试处理脚本中的任何远程故障。


5

如果您确实需要捕获错误消息,可以尝试以下操作:

#!/bin/bash
result=`ssh myapp 'mkdir /some/dir' 2>&1`
if [[ -n $result ]]; then
    echo "the following error occurred: $result"
fi

这样,您就可以将标准错误输出重定向到标准输出,并将ssh命令的输出保存到$result。如果您只需要错误代码/退出状态,请参阅此答案

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.