[英]How can I get a return code from an ssh command inside a bash function, that is sourced inside another script?
[英]Get return code of ssh command in bash
我需要在我的bash脚本中获取ssh命令的返回/错误代码。 该命令使用applescript将远程计算机上的文件移至垃圾箱。 这是一个较大的脚本的一部分:
ssh $login "bash -s" <<-EOF
error=(osascript -e "tell application \"Finder\" to move POSIX file \"$remote_filepath\" to trash");
[[ -n "$error" ]] && { echo -e "\nCannot move file to trash on remote mac"; exit 1; };
EOF
# echo $?; exit
[[ $? -ne 0 ]] && exit 1
# more code ...
我的目标是,如果osascript失败,则使ssh命令以代码1退出,这样我就可以捕获错误并中止脚本的其余部分。
ssh成功运行,文件确实移至回收站。 显然osascript运行良好,因为未显示错误消息。 ssh的返回码仍然是1(我用echo $?
语句检查了它。这就是我遇到的问题。对于在这里出什么问题的任何见解,我将不胜感激。
问题是[[ -n "$error" ]]
命令将错误代码设置为1。您需要使用该测试的否定。 尝试:
[[ -z "$error" ]] || { echo -e ...
在osascript
所有问题osascript
没有返回真正的错误代码之后,我决定只检查文件是否完全移动,如下所示:
# move file to trash on remote mac
ssh $login "bash -s" <<-EOF
osascript -e "tell application \"Finder\" to move POSIX file \"$remote_filepath\" to trash" > /dev/null;
EOF
[[ ! -e "$remote_filepath" ]] || { printf "\nCannot move file to trash on remote mac" && exit 1; }
对我来说似乎更简单,更容易维护。 感谢大家的投入!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.