How can I get the default browser name in bash script on Mac OS X
You can grep/awk
the launch services preferences list to find out which browser is set as default:
x=~/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist; \plutil -convert xml1 $x; \grep 'https' -b3 $x | awk 'NR==2 {split($2, arr, "[><]"); print arr[3]}'; \plutil -convert binary1 $x
This sets a variable (x
) to the launch services preferences list, then converts it using plutil
to xml
format so we can grep
it. We locate the string we're looking for (https
) then output the result. The final step is to convert the plist back to binary
format.
If chrome is set to be default you will get:
Result:
com.google.chrome
No need to convert, use this script:
plutil -p ~/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist | grep 'https' -b3 |awk 'NR==3 {split($4, arr, "\""); print arr[2]}'
Getting Default Browser
The following command will print the ID of the default application for https
:
defaults read com.apple.LaunchServices/com.apple.launchservices.secure LSHandlers \ | sed -n -e '/LSHandlerURLScheme = https;/{x;p;d;}' -e 's/.*=[^"]"\(.*\)";/\1/g' -e x
If Firefox was your default browser, you would get org.mozilla.firefox
.
Explanation
The script reads the corresponding system defaults using the defaults
command and extracts the ID from the above line of the https
matching line (more on that can be read up at https://unix.stackexchange.com/questions/206886/print-previous-line-after-a-pattern-match-using-sed).
Getting Default Application
You could wrap a function around it and allow passing the scheme:
# Returns the default app for the specified scheme (default: https).default_app() { local scheme=${1:-https} defaults read com.apple.LaunchServices/com.apple.launchservices.secure LSHandlers \ | sed -n -e "/LSHandlerURLScheme = $scheme;/{x;p;d;}" -e 's/.*=[^"]"\(.*\)";/\1/g' -e x}
The call would now be
default_app# ordefault_app https
Interacting with Default Browser/Application
I guess you would like to do something with the ID as well.
Integrating with Apple Script can be achieved with application id
.
The following shell script runs an Apple Script that activates / focusses / brings to front your default browser:
osascript <<APPLE_SCRIPTtell application id "$(default_app)" activateend tellAPPLE_SCRIPT
Same as a one-liner:
osascript -e "tell application id \"$(default_app)\"" -e 'activate' -e 'end tell'