bash - ssh bash -c exit status does not propagate
问题描述
According to man ssh
and this previous answer, ssh should propagate the exit status of whatever process it ran on the remote server. I seem to have found a mystifying exception!
$ ssh myserver exit 34 ; echo $?
34
Good...
$ ssh myserver 'exit 34' ; echo $?
34
Good...
$ ssh myserver bash -c 'exit 34' ; echo $?
0
What?!?
$ ssh myserver
ubuntu@myserver $ bash -c 'exit 34' ; echo $?
34
So the problem does not appear to be either ssh or bash -c
in isolation, but their combination does not behave as I would expect.
I'm designing a script to be run on a remote machine that needs to take an argument list that's computed on the client side. For the sake of argument, let's say it fails if any of the arguments is not a file on the remote server:
ssh myserver bash -c '
for arg ; do
if [[ ! -f "$arg" ]] ; then
exit 1
fi
done
' arg1 arg2 ...
How can I run something like this and effectively inspect its return status? The test above seems to suggest I cannot.
解决方案
问题是报价丢失了。ssh
只是连接参数,它不会重新引用它们,所以您在服务器上实际执行的命令是:
bash -c exit 34
该-c
选项只接受一个参数,而不是所有剩余的参数,所以它只是在执行exit
;34
被忽略。
如果你这样做,你会看到类似的效果:
ssh myserver bash -c 'echo foo'
它只会回显一个空行,而不是foo
.
你可以通过给一个参数来修复它ssh
:
ssh myserver "bash -c 'exit 34'"
或加倍引号:
ssh myserver bash -c "'exit 34'"
推荐阅读
- javascript - 我是否为 mediasoup 打开了错误的端口?
- excel - 使用 SaveAs 函数时 VBA 对象不支持此属性或方法
- sqlite - 与自身联合表并打印独特的对
- xpath - 找到负载类型为“40 年固定”且子类型为“A”的比率
- java - 如何在 jooq 中使用别名进行排序
- amp-html - 为什么 AMP 页面的 Google 搜索结果有“IIS Windows Server”?
- django - 完整性错误处理和个性化消息
- django - 如何在 form_valid 中删除模型中的所有多对多关系?
- php - 在 WooCommerce 订单列表中显示 Dokan 自定义订单元数据
- android - 如何构建/调试 Uno 平台应用程序的 Android 头。在 Linux 下?