Reputation: 142
I have a shell script that has the first line (after #! /bin/sh
):
IP=$(curl ifconfig.me)
Sometimes the script will execute and be done within 3 seconds other times it times out at this point in the script (I know because I use notify-send to display IP on the next line).
More often than not I will have to run the script several times in order to get it to complete (I use CTRL+C to interrupt).
I would love to be able to run the script once and if it hasn't completed within 10 seconds it exits and runs itself again, and keeps looping until it gets an exit code 0 within a 10 second time frame, or to fix the reason why it doesn't just complete the first time round.
I have seen a number of other solutions to get a timeout going but I haven't seen any instructions that make sense to me and thus haven't been able to implement them. For example this one.
I was thinking of giving the ulimit version a try since I'm now more experienced with python than I used to be but I'm not sure it makes sense to use a script to run a script.
I have tried using sleep but all I can seem to do is get it to pause running the script and thus it never completes.
The rest of the script sets rules for iptables
.
Upvotes: 2
Views: 1383
Reputation: 2164
You may use the timeout
command from coreutils
while ! IP=$(timeout 3 curl ifconfig.me)
do
sleep 1
done
Upvotes: 0
Reputation: 346
What you need to do is tailor the curl command you are using. There are a number of options which might help:
curl --connect-timeout 3 --max-time 10 --retry 3 ifconfig.me
This tells the curl command to timeout if the connection isn't established within 3 seconds, it will timeout if the complete data transfer takes more than 10 seconds, and it will retry 3 times. Adjust as appropriate!
There are a few other parameters you could set, check man curl as well.
Upvotes: 3
Reputation: 249123
You should use the curl --max-time
option. Then it will fail if it doesn't complete within a specified number of seconds.
Upvotes: 1