从 ssh 捕获退出状态代码

San*_*jay 1 shell-script exit

#!/bin/bash
RET=0
export RET
{
ssh -q -t  user@host <<EOF
echo "hello there "
exit 10
EOF
RET=$?
echo "Out is" $RET
} &
echo "RET is $RET"
################## End
Run Code Online (Sandbox Code Playgroud)

我得到 RET 0 OUT 是 10

如何在外部块中获得正确的退出状态代码。我需要查看退出代码 10。

ilk*_*chu 5

您要么需要在前台运行该命令

$ (exit 10)
$ echo $?
10
Run Code Online (Sandbox Code Playgroud)

或者如果它在后台运行,明确地wait为它:

$ (sleep 3; exit 10) &
$ wait %%                      # %% refers to the current (last) job
$ echo $?
10
Run Code Online (Sandbox Code Playgroud)

或者通过为 指定进程 ID 而不是作业号wait

$ (sleep 3; exit 10) & pid=$!
$ wait $pid                    # $! holds the PID of the last background process
$ echo PID $pid exited with code $?
Run Code Online (Sandbox Code Playgroud)