bash - 如果 heredoc 命令失败,如何退出脚本

标签 bash shell ssh heredoc

我的 shell 脚本中有一个 ssh heredoc,如果 heredoc 中的其中一个命令出现错误,我该如何退出我的 shell 脚本。

我的shell脚本是这样的

#!/bin/bash

set -o errexit

loginto_vm() {

    ssh host@IP << ENDSSH

ls n1n

cd n1n

ENDSSH

    echo 'done'

}

loginto_vm

这里如果“n1n”不存在则从 ssh heredoc 退出并打印 echo 语句,但我希望它从脚本中退出

最佳答案

您可以在 heredoc 中检查任何关键命令的退出状态并在出现错误时退出 ssh - 然后检查 ssh 退出状态以退出您的脚本

ssh host@IP <<ENDSSH
ls n1n || exit 1
cd n1n || exit 2
ENDSSH
(($?)) && exit 1
echo 'done'

关于bash - 如果 heredoc 命令失败,如何退出脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39102280/

相关文章:

regex - 在 Awk 中使用正则表达式

json - 使用jq将多个JSON的一个属性连接到一个文件中

linux - 远程 SSH 命令在 Linux 中不起作用

shell_exec 中的 PHP sudo

linux - 如何使用本地参数运行远程 bash 脚本

bash - shell脚本通过空格传递参数

linux - if else 语句中出现意外的文件结尾错误

linux - Emacs shell 模式 SSH session 中的 Tab 补全

php - 通过 SSH 进行 MySQL 查询,在第 1 行给出错误 1064 (42000)

python 预期: SSHing then updating the date