在shell脚本中返回heredoc外部的状态

1dkrff03  于 2023-01-21  发布在  Shell
关注(0)|答案(1)|浏览(93)

我有一个用例,我需要获取嵌套的heredoc的返回状态,如果命令失败,那么在heredoc内部,主shell应该退出。

ssh username@<ip address> << EOF1
su - user2 << EOF2
 command1 
 check return status if >1 then exit
EOF2
Check return status of EOF2 if >1 then exit
command2
EOF1

在本例中,我的脚本无法捕获返回代码,即使command1失败,它也会执行command2
是否有可能获得嵌套heredoc的返回状态并退出主shell?

qlvxas9a

qlvxas9a1#

您应该退出su -并显示错误,然后在测试错误代码后运行command2。

ssh username@<ip address> << EOF1
if  su - user2 << EOF2
    if false; then # Replace [false] with your command1
        echo "Successful from [su]"
    else
        echo "Failed from [su]"
        exit 1
    fi
EOF2
then
    echo Running command2
else
    echo "command1 failed."
fi
EOF1

相关问题