I have a simple bash script that disables a USB port if there is no internet connection and after five seconds enables it again. But SOMETIMES it fails, the script disables the port but is not enabled again. Note that I only have a one USB port. This is my script:


while true 
    sleep 10                                                
    if ping -c 2 google.com >> /dev/null 2>&1;then                        
        echo $(date  +"%r") >> /root/log.txt
        echo "Conectado a SopelaBari" >> /root/log.txt
        echo $(date  +"%r") >> /root/log.txt
        echo "Sin conexion" >> /root/log.txt
        echo '2-1' |tee /sys/bus/usb/drivers/usb/unbind
        sleep 5
        echo '2-1' |tee /sys/bus/usb/drivers/usb/bind
        sleep 5
    sleep 30 

I am running Ubuntu 14.04.05 and the script is run as root with crontab. As I am quite unfamiliar with bash: So I know that the code is improvable and probably fails due to some mistake I made.

Thanks, Ander.

  • I don't see anything obviously wrong with your script. Try adding 2> /tmp/script.logfile to the end of your crontab line and see if any error output is generated when it doesn't work. You could also try increasing the sleep 5 10 or 20 or so, to be sure it isn't a problem with how long it takes for the port to be disabled/enabled. – terdon Feb 11 at 16:38
  • @terdon, thanks for your answer. Do I have to create 2> /tmp/script.logfile directory or is automatically created? I don't think time is a problem, normally it takes less than 1 sec to enable/disable the port. – Andermutu Feb 11 at 16:42
  • The /tmp directory is created by default, just add 2> /tmp/script.logfile and that will create a file called script.logfile in /tmp. And yes, I agree that it should take less than a second but since you say it usually works, but sometimes does not, then we're looking for something strange. So maybe it sometimes takes longer. – terdon Feb 11 at 16:47
  • Thanks @terdon. I added the script.logfile and increased the time. I will need some time to reproduce the error. I will tell you something as soon as I can. – Andermutu Feb 11 at 16:53
  • 1
    Great! When you have more details, please edit your question and add them there (don't write "edit" or anything, just write your question as if you had included this information from the beginning). That way, the next person to read your question will have all the information. – terdon Feb 11 at 17:20

Your Answer


By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.