簡體   English   中英

在Shell腳本中建立遠程連接時如何捕獲錯誤

[英]How to Catch an Error While Establishing Remote Connection in Shell Script

這就是我的shell腳本的一部分。

#! /bin/sh
sftp -i $IdentityFile $ServerAddress << EOF
command 1 #Execute in the remote
command 2 #Execute in the remote
bye
EOF
command 3 #Execute locally

根據我目前對腳本的了解,如果命令執行失敗,則控制權僅傳遞給下一個命令。 但是,如果在上述塊中sftp命令無法建立網絡連接怎么辦? 這是否意味着command 1command 2將在本地執行? 還是控制跳到command 3

如何在sftp中捕獲可能的錯誤並將控件定向到command 3 如果可以的話,我可以使用來檢測錯誤? 變量,采取某些先發制人的行動? 一些指導會很棒。

有幾件事要做。

首先,您需要將輸入提取為一個函數,以允許使用command3進行管道傳輸 ,這將更加清晰:

function sfpInstruction() {
cat << EOF
command 1
command 2
bye
EOF
}

因此,您的sftp指令可以更改為:

tmpFile="/tmp/errorFile.txt"
sftp -i $IdentityFile $ServerAddress $( sfpInstruction ) 2>"$tmpFile" || command3

這樣的方式:

  • 您的錯誤文件中所有錯誤消息都超出了
  • 在任何情況下,如果sftp以失敗狀態退出(不為0),則GNU / Bash將執行command3
  • 如果您還希望Command3讀取/檢查/解析錯誤消息,則可以為其指定“ $ tmpFile”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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