2017-09-25 52 views
2

我正在使用ssh從本地shell腳本運行遠程shell腳本。下面是我的本地shell腳本中的代碼:如何將狀態碼從遠程運行的shell腳本返回到本地shell腳本

ssh [email protected]_server '/bin/bash' << EOF 
    if remote_shell_script.sh ; then 
      echo 'Script executed successfully' 
    else 
     echo 'Script failed' 
    fi 
EOF 

上述腳本工作正常。但是我無法將狀態碼返回到本地可以使用的本地shell腳本。我想在EOF..EOF裏面返回一個狀態碼(0,1),這些語句可以在我的本地腳本中捕獲,然後相應地採取行動。我怎樣才能做到這一點?

回答

3

EOF塊的退出代碼將被傳回到外殼。您可能遇到的問題是正在吞嚥remote_shell_script.sh的退出代碼。你可以通過幾種方法解決這個問題。一個是exit與適當的退出代碼。

ssh [email protected]_server '/bin/bash' << EOF 
    if remote_shell_script.sh ; then 
     echo 'Script executed successfully' 
     exit 0 
    else    
     echo 'Script failed' 
     exit 1 
    fi  
EOF 

echo "Exit code = $?" 

更簡單的方法是將檢查邏輯移動到本地服務器。在這種情況下,你甚至不需要這裏的EOF文件。

if ssh [email protected]_server remote_shell_script.sh; then 
    echo 'Script executed successfully'   
else    
    echo 'Script failed'    
fi