1

I have a 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:

#!/bin/bash

while true 
do 
    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
    else
        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
    fi 
    sleep 30 
done

I am running Ubuntu 14.04.05 and the script is run as root with crontab.

  • 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 '18 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 '18 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 '18 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 '18 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 '18 at 17:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.