-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlocation-switch.sh
executable file
·96 lines (78 loc) · 2.85 KB
/
location-switch.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/bin/bash
# A simple script used to switch from one network location to another, each location
# has specific parameters and is based on different interfaces.
#
# Author: [email protected]
# Last Update: 21st November 2024
# default network location
DEFAULT_LOCATION="Automatic"
# new location
KNOWN_LOCATIONS=(
# add your locations here
# m:00:11:22:33:44:55:Home
)
# display notification when location changes
NOTIFICATION=1
# get current location
CURRENT_LOCATION=$(networksetup -getcurrentlocation)
# wifi interface
WIFI_INTERFACE=en0
# logging
DATE_COMMAND="date -Iseconds"
# set new location to default location
NEW_LOCATION=$DEFAULT_LOCATION
IFCONFIG_OUTPUT=$(ifconfig)
WIFI_OUTPUT=$(ipconfig getsummary $WIFI_INTERFACE)
for loc in "${KNOWN_LOCATIONS[@]}"; do
# check if the item starts with "m" (MAC address)
if [[ $loc == m:* ]]; then
# extract the MAC address and location name from the item
MAC="${loc:2:17}"
LOCATION="${loc:20}"
# check if the mac address matches any ethernet interface
if (echo "$IFCONFIG_OUTPUT" | grep -q -E "$MAC"); then
# set new location to the item location
NEW_LOCATION=$LOCATION
if [[ "$1" == "-v" ]]; then
echo "[$($DATE_COMMAND)]: MAC address matched \"$MAC\", new location to set: \"$NEW_LOCATION\""
fi
break
fi
# check if the item starts with "s" (SSID)
elif [[ $loc == s:* ]]; then
# extract the SSID and locationname from the item
SSID="$(echo $loc | cut -d: -f2)"
LOCATION="${loc:3+${#SSID}}"
# check if matched ssid is currently connected
if (echo "$WIFI_OUTPUT" | grep -q -E "SSID : $SSID\$"); then
# set new location to item location
NEW_LOCATION=$LOCATION
if [[ "$1" == "-v" ]]; then
echo "[$($DATE_COMMAND)]: SSID matched: \"$SSID\", new location to set: \"$NEW_LOCATION\""
fi
break
fi
else
if [[ "$1" == "-v" ]]; then
echo "[$($DATE_COMMAND)]: Unknown location format: \"$loc\""
fi
exit 1
fi
done
# switch to new location only if it changed from current location
if [ "$CURRENT_LOCATION" != "$NEW_LOCATION" ]; then
output=$(scselect "$NEW_LOCATION")
if [[ "$1" == "-v" ]]; then
echo "[$($DATE_COMMAND)]: $output"
echo "[$($DATE_COMMAND)]: location changed from $CURRENT_LOCATION to $NEW_LOCATION"
fi
# display a notification
if [ "$NOTIFICATION" == 1 ]; then
echo "[$($DATE_COMMAND)]: sending notification"
osascript -e "display notification \"Network location switched from $CURRENT_LOCATION to $NEW_LOCATION\" with title \"Network Location Switcher\""
fi
else
if [[ "$1" == "-v" ]]; then
echo "[$($DATE_COMMAND)]: location not changed from $CURRENT_LOCATION"
fi
fi