简体   繁体   English

如何通过ssh获取远程命令的退出码

[英]How to get exit code of remote command through ssh

I am running a script from remote machine via ssh:我正在通过 ssh 从远程机器运行脚本:

ssh 'some_cmd;my_script'  

Now, I want to store exit status of shell script on my local machine.现在,我想在本地机器上存储 shell 脚本的退出状态。 How can I do it?我该怎么做?

Assuming nothing goes wrong with ssh itself, its exit status is the exit status of the last command executed on the remote host.假设ssh本身没有问题,它的退出状态就是在远程主机上执行的最后一个命令的退出状态。 (If something does go wrong, its exit status is 255.) (如果确实存在错误,退出状态是255)

$ ssh remotehost exit 13
$ echo $?
13

I had same problem.我有同样的问题。 I don't think the previous answers will work.我不认为以前的答案会奏效。 At least they did not work for me.至少他们对我不起作用。

This is what worked for me.这对我有用。 I ran my command and displayed the exit code and captured it in a variable.我运行了我的命令并显示了退出代码并将其捕获在一个变量中。

Ensure you protect the $?确保您保护 $? sign with the escape sequence \\用转义序列符号 \\

# retcode=$(ssh test@1.2.3.4 "grep -q test /etc/passwd ; echo \$? " 2>/dev/null)
# echo $retcode
# 1

Cheers.干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM