Terminal Theme – How to Programmatically Set Profile

automationbashterminal

Context for this question:
I'm writing a bash script to automatically setup any Mac with my tools/preferences, ideally with one command if possible.

The question:
I have a .terminal theme file that i use and i'd like for the script to be able to set it as the default terminal profile without having to do it through the GUI after running my script, is there a command for this?

Best Answer

Alright i've figured out a solution:

To set the terminal theme programmatically you need to write to your systems preferences. So the easiest way that i found to do this was to extract the user preferences from an existing mac first. This assumes that you've already imported your .terminal file into the profiles of the Terminal on your existing machine. So first on the existing mac you need to run the following (My theme is called Material-Theme, replace that part with your own):

plutil -extract Window\ Settings.Material-Theme xml1 -o - ~/Library/Preferences/com.apple.Terminal.plist > theme.xml

This will create a theme.xml file for you to use in your script. The next thing is just to edit the file a little. This could be automated, but if you're like me you only need to do this part once, so i did this manually. Open the file and remove the surrounding xml at the top and bottom so that all you have is the dict, mine looked like this for reference: https://pastebin.com/zfXFRY2e.

Now in your script on the new machine you can just run the following to insert this theme into your user preferences:

theme=$(<theme.xml)
plutil -replace Window\ Settings.Material-Theme -xml "$theme" ~/Library/Preferences/com.apple.Terminal.plist
defaults write com.apple.Terminal "Default Window Settings" -string "Material-Theme"
defaults write com.apple.Terminal "Startup Window Settings" -string "Material-Theme"

Now after running the above when you fully close the Terminal app and restart it, your theme should be the default. This process can probably be improved but this worked for me!

Note you might also want to run defaults read com.apple.Terminal and check if there are any other keys that are relevant to your theme. In my case i found "NSWindow Frame TTWindow Material-Theme" = "0 327 640 450 0 0 1280 777 "; so my script includes this as well defaults write com.apple.Terminal "NSWindow Frame TTWindow Material-Theme" -string "0 327 640 450 0 0 1280 777 "