[英]How to use exit status inside timeout bash -c command
I'm running a small script to essentially poll a newly created AWS instances for SSH access. 我正在运行一个小脚本,以实质上轮询新创建的AWS实例以进行SSH访问。 I want it to poll up to 60 seconds, which is why I am using the linux
timeout
command. 我希望它轮询最多60秒,这就是为什么我使用linux
timeout
命令的原因。
I've got a small script that runs a while loop within a timeout command. 我有一个小的脚本,可以在超时命令中运行while循环。
"Full" script for reference. “完整”脚本供参考。 You can assume the IP address is correct
您可以假设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"
The key part of the polling is 轮询的关键部分是
ssh -oConnectTimeout=2 -oStrictHostKeyChecking=no -q ${INSTANCE_IP} exit
response_code=$?
The problem is that the exit status (ie $?) is always empty, resulting in this output: 问题在于退出状态(即$?)始终为空,从而导致以下输出:
line 4: ((: == 0 : syntax error: operand expected (error token is "== 0 ")
Failed to connect by ssh. Trying again in 5 seconds...
How can I use the exit status when the commands are executed with a bash -c
command? 用
bash -c
命令执行命令时如何使用退出状态?
What happens in your script, is that $?
您的脚本中会发生什么,那是
$?
is expanded before bash is even run. 甚至在 bash运行之前就被扩展了。 It's always going to be zero or empty.
它总是为零或为空。
You could do change the quotes, from "
to '
. Remember to expand variables that you want to expand properly. Alternatively, you could just change escape $?
into \\$?
. 你可以做改变报价,从
"
到'
记住扩大要适当扩大变量。另外,你可以只改变逃脱$?
为\\$?
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'
Or use a function: 或使用功能:
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.