gpt4 book ai didi

linux - 如何在超时 bash -c 命令中使用退出状态

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:45 25 4
gpt4 key购买 nike

我正在运行一个小脚本来轮询新创建的 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"

关于linux - 如何在超时 bash -c 命令中使用退出状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57269084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com