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