Apple - Turn Wifi off/on with a single key?
Thanks to budakpisang for this:
In Terminal, run
networksetup -listnetworkserviceorder | sed -n '/Wi-Fi/s|.*Device: \(.*\)).*|\1|p'
to get your WiFi network device (usually it's en0
or en1
, depending on the Mac model you have). Substitute it for en1
in the following steps
You can turn wifi off and on with these commands
networksetup -setairportpower en1 off
networksetup -setairportpower en1 on
Here's a one-liner to toggle between on and off
networksetup -getairportpower en1 | grep "On" && networksetup -setairportpower en1 off || networksetup -setairportpower en1 on
Create a keyboard shortcut that runs a shell command
Start Automator, and create a new Service.
Set "Service receives selected: to "no input" in "any application".
Add an action named "Run Shell Script". It's in the Utilities section of the Actions Library.
Insert the bash command you want into the text box and test run it using the Run button (top right). It should do whatever the script does (off, on or toggle), and there should be green ticks below the Action.
Save it, giving it a service name you can remember.
Go to System Preferences -> Keyboard, and go to the Shortcuts tab
Go to the Services section, and scroll down to General - you should find your service there. If you select the line, you can click "add shortcut" and give it a keyboard shortcut.
A slight improvement on the great answer of Drew Ogryzek worked (better) for me. The following script doesn't make any assumptions on which network adapter is used for WiFi:
set_wifi_on_or_off() {
networksetup -getairportpower en${n} | grep ": ${1}";
if test $? -eq 0;
then
echo WiFi interface found: en${n};
eval "networksetup -setairportpower en${n} ${2}"
return 0;
fi
return 1;
}
for n in $(seq 0 10);
do
if set_wifi_on_or_off "On" "off"; then break; fi;
if set_wifi_on_or_off "Off" "on"; then break; fi;
done