raspberry pi – Raspi WLAN restart

I have a Raspi Zero W connected via WLAN with a FritzBox. Unfortunately the distance is at its limit, thus the connection is not very stable. I wrote a cron script to ping the router and if it can’t be reched I want to restart the WLAN connection. But everything I tried did not succeed unless I reboot the entire device. How to I completly reset my WLAN with the same effect like a reboot?

This is my cron script, I see in the log file that it always executes a reboot:

ping -c 5 -i 2 "${IPADDRESS}" > /dev/null 2>&1

if [ $? -ne 0 ]
then
  echo "$(date '+%Y-%m-%d %H:%M:%S') Ping failed. Restart interface." >> "${LOGFILE}"
  tail -n 100 "${LOGFILE}" >> "${LOGFILETMP}" && mv "${LOGFILETMP}" "${LOGFILE}"
  ifdown wlan0
  sleep 10
  ifup wlan0
  sleep 60
  ping -c 5 -i 2 "${IPADDRESS}" > /dev/null 2>&1

  if [ $? -ne 0 ]
  then
    echo "$(date '+%Y-%m-%d %H:%M:%S') Ping failed. Reconfigure if." >> "${LOGFILE}"
    tail -n 100 "${LOGFILE}" >> "${LOGFILETMP}" && mv "${LOGFILETMP}" "${LOGFILE}"
    ifconfig wlan0 down
    sleep 10
    ifconfig wlan0 up
    sleep 60
    ping -c 5 -i 2 "${IPADDRESS}" > /dev/null 2>&1

    if [ $? -ne 0 ]
    then
      echo "$(date '+%Y-%m-%d %H:%M:%S') Ping failed. Reconfigure ip." >> "${LOGFILE}"
      tail -n 100 "${LOGFILE}" >> "${LOGFILETMP}" && mv "${LOGFILETMP}" "${LOGFILE}"
      ip link set wlan0 down
      sleep 10
      ip link set wlan0 up
      sleep 60
      ping -c 5 -i 2 "${IPADDRESS}" > /dev/null 2>&1

      if [ $? -ne 0 ]
      then
        echo "$(date '+%Y-%m-%d %H:%M:%S') Ping failed. System is going to reboot." >> "${LOGFILE}"
        tail -n 100 "${LOGFILE}" >> "${LOGFILETMP}" && mv "${LOGFILETMP}" "${LOGFILE}"
        reboot
      fi
    fi
  fi
fi

Read more here: Source link