I have the following script that disconnects from the current WiFi network and reconnects based on the content of wpa_supplicant.conf:
#!/bin/bash
if iwgetid; then
sudo wpa_cli terminate
sudo ip addr flush wlan0
sudo ip link set dev wlan0 down
sudo rm -r /var/run/wpa_supplicant > /dev/null
fi
sudo wpa_supplicant -B -i wlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf > /dev/null 2>&1
sudo service ntp restart
sudo ip link set dev wlan0 down
sudo ip link set dev wlan0 up
sudo dhclient wlan0
The problem is, if the credentials in wpa_supplicant are not correct (these are based on user input in my app, so very possible), dhclient hangs for quite a while, trying to connect to a DHCP server and assign an IP address before eventually failing.
Is there a way to test that the credentials are correct before calling dhclient?