從 ssh 捕獲退出狀態代碼

從 ssh 捕獲退出狀態代碼
#!/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

我得到 RET 0 OUT 是 10

如何在外部區塊中獲得正確的退出狀態代碼。我需要查看退出代碼 10。

答案1

您需要在前台運行該命令

$ (exit 10)
$ echo $?
10

或者,如果它在背景運行,則明確地wait為其運行:

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

或透過指定進程 ID 而不是作業號wait

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

相關內容