簡體   English   中英

在bash中獲取ssh命令的返回碼

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM