I need to do some script, which find out if the connection to the Wi-Fi was successful or not.

I have Wi-Fi configuration in /etc/wpa_supplicant.conf.

I know how to add SSID and PSK to this file and connect to it.

I mean something like this:

variable ssid = "test"
variable psk = "psk"

try to connect to {ssid, psk}

if(connection == True) {
    add {ssid, psk} to the /etc/wpa_supplicant.conf
else {
    echo("PSK is wrong, try it again.")

I don't know how to do try to connect to {ssid, psk}.


killall wpa_supplicant 

sleep 1

wpa_supplicant -i wlan0 -c<(wpa_passphrase "$1" "$2") -B \
               -C /var/run/wpa_supplicant \
               -f /etc/wpa_supplicant.log
sleep 3

wpa_status=$(wpa_cli  status | grep wpa_state | cut -d"=" -f2)

if test  "$wpa_status" = "COMPLETED"
    echo "$wpa_status"
    wpa_passphrase "$1" "$2" >> /etc/wpa_supplicant.conf
    echo " $wpa_status : Try again"
    exit 1

Usage (as root):

# ./script ssid password 

The -f will create a log file it can be used instead of wpa_cli status command to get the status of wlan0 interface.

wpa_passphrase will save the correct "ssid" and "password" to /etc/wpa_supplicant.conf.

The /etc/wpa_supplicant.conf should contain:


Assign an IP address to wlan0 if you need to connect ( dhclient , dhcpcd , ip ...)

@TSJNachos117 comment: you can replace grep and cut with awk:

 wpa_cli status | awk -F = '{if($0 ~ /wpa_state/) print $2}'
  • 1
    FYI, in the wpa_status= line, you can replace grep and cut with awk: wpa_cli status | awk -F = '{if($0 ~ /wpa_state/) print $2}'. Do with that what you will. :-) – TSJNachos117 Apr 13 at 22:08
  • @TSJNachos117 Thank you. – GAD3R Apr 16 at 15:12
  • You're welcome. – TSJNachos117 Apr 17 at 20:09

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.