[英]In bash script, how to use function exit status in while loop condition
[英]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.