簡體   English   中英

如何在超時bash -c命令中使用退出狀態

[英]How to use exit status inside timeout bash -c command

我正在運行一個小腳本,以實質上輪詢新創建的AWS實例以進行SSH訪問。 我希望它輪詢最多60秒,這就是為什么我使用linux timeout命令的原因。

我有一個小的腳本,可以在超時命令中運行while循環。

“完整”腳本供參考。 您可以假設IP地址正確

  # poll for SSH access
  timeout_threshold=60
  INSTANCE_IP=199.199.199.199
  timeout $timeout_threshold bash -c "while true; do
    ssh -oConnectTimeout=2 -oStrictHostKeyChecking=no -q ${INSTANCE_IP} exit
    response_code=$?
    if (( response_code == 0 )); then
      echo \"Successfully connected to instance via SSH.\"
      exit
    else
      echo \"Failed to connect by ssh. Trying again in 5 seconds...\"
      sleep 5
    fi
  done"

輪詢的關鍵部分是

    ssh -oConnectTimeout=2 -oStrictHostKeyChecking=no -q ${INSTANCE_IP} exit
    response_code=$?

問題在於退出狀態(即$?)始終為空,從而導致以下輸出:

line 4: ((: == 0 : syntax error: operand expected (error token is "== 0 ")
Failed to connect by ssh. Trying again in 5 seconds...

bash -c命令執行命令時如何使用退出狀態?

您的腳本中會發生什么,那是$? 甚至 bash運行之前就被擴展了。 它總是為零或為空。

你可以做改變報價,從"'記住擴大要適當擴大變量。另外,你可以只改變逃脫$?\\$?

timeout "$timeout_threshold" bash -c 'while true; do
    ssh -oConnectTimeout=2 -oStrictHostKeyChecking=no -q '"${INSTANCE_IP}"' exit
    response_code=$?
    if (( response_code == 0 )); then
      echo "Successfully connected to instance via SSH."
      exit
    else
      echo "Failed to connect by ssh. Trying again in 5 seconds..."
      sleep 5
    fi
  done'

或使用功能:

connect() {
    # I pass the instance as the first argument
    # alternatively you could export INSTANCE_IP from parent shell
    INSTANCE_IP="$1"
    while true; do
       ssh -oConnectTimeout=2 -oStrictHostKeyChecking=no -q "$INSTANCE_IP" exit
       response_code=$?
       if (( response_code == 0 )); then
          echo "Successfully connected to instance via SSH."
          exit
       else
          echo "Failed to connect by ssh. Trying again in 5 seconds..."
          sleep 5
       fi
    done
}

timeout_threshold=60
INSTANCE_IP=199.199.199.199

# function needs to be exprted to be used inside child bashs
export -f connect

timeout "$timeout_threshold" bash -c 'connect "$@"' -- "$INSTANCE_IP"

暫無
暫無

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

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