I try to connect to a specific WiFi network in a bash script on a Mac.

Two things I want to achieve:

  1. Connect to the specified network. I have tried networksetup -setairportnetwork en0 [network_ID], and I could see from the top menu bar that the Mac is trying to connect to the network but eventually it failed. I should note that the network is password protected, and the password is stored in the keychain as I don't need to type it in when I join this network manually.

  2. Pause the execution of the rest of script until the connection is successfully established.

Any suggestion?

1 Answer 1


1) Connecting Wireless Network
You want to add your password. Although the passkey for my WiFi network BSSID was in my keychain, I could only switch to it and successfully login by adding the passkey directly to the command line in clear text. Nothing else worked.

networksetup -setairportnetwork [en0] [network_BBSSID] [passkey]

2) Pausing script until connected
You can simply test the error code of the command above (echo $?). Be careful as networksetup error codes are not trivials, grepping for "failed" may help:
networksetup -setairportnetwork en0 mywifi mypass | grep -ic "failed"

if the result is 0 you should be good. You could also test directly for actual connectivity rather than simply being connecting to the wifi (better option imho) e.g you could check that you can ping a host on your network or on the internet. You should put all this in a while : loop which will retry the command until the result is 0. Or you can add a read statement to your command that will pause the script (my understanding of your question).

Last you may want to add a timeout to kill networksetup in case no network is being joined after a while: timeout command, part of gnu coreutils may come in handy. It can be installed via the brew package manager: brew install coreutils.

3) One liner suggestion
! gtimeout 10s networksetup -setairportnetwork en0 mywifi mypass >/dev/null && echo 1 || { ping -oq www.apple.com 2>&- >/dev/null && echo "Connected" || read -n1 -r -p "Connection failed. Press any key to continue..." ; } ;

gtimeout : gnutls add the g prefix by default to its commands to avoid mixing up with existing default utilites of the same name
/dev/null, 2>&- : avoid printing the outputs and error codes of the various commands
read -n 1 : pausing until key press

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .