记录 ssh shell 的输出并保留退出状态

Ejj*_*esh 2 bash pipe shell-script exit-status

我有一些脚本要server-2通过 ssh from在远程服务器()上执行server-1,我必须将该输出写入名为file.logon的日志文件中server-1

我正在尝试这个: sc.sh

echo 'testing'
cp $HOME/dir1/file1 $HOME/dir2
Run Code Online (Sandbox Code Playgroud)

现在,sc.sh通过 ssh执行:

sshpass -p 'psswd' ssh username@server-2 "bash -s" < sc.sh | tee -a file.log
if [ $? -eq 0]; then
  echo "successfully executed the script file"
  .
  .
  .
else
  echo "failed copying due to incorrect path"
fi
Run Code Online (Sandbox Code Playgroud)

现在由于tee -a file.log命令,即使我在脚本文件中的命令失败,它也将始终返回 0。如何写入日志文件,并应ssh根据ssh命令退出代码检查应在命令后工作的 if 条件?

Ejj*_*esh 5

检查${PIPESTATUS[0]}对我有用...

if [ ${PIPESTATUS[0]} -eq 0 ]; then
  echo "successfull"
fi
Run Code Online (Sandbox Code Playgroud)

echo ${PIPESTATUS[*]} 打印所有管道命令的退出代码。