duti - macOS 預設應用程式管理工具

什麼是 duti?

duti 是一個 macOS 命令行工具,用於設定特定文件類型或 URL scheme 的預設處理應用程式。相較於在系統偏好設定中逐一修改,duti 讓你可以透過指令批次管理預設應用程式。

安裝

使用 Homebrew 安裝:

1
brew install duti

基本用法

查詢目前的預設應用程式

查詢特定檔案類型的預設應用程式:

1
duti -x txt

輸出範例:

1
2
3
Visual Studio Code
com.microsoft.VSCode
/Applications/Visual Studio Code.app

設定預設應用程式

設定預設應用程式的基本語法:

1
duti -s <bundle_id> <uti_or_extension> <role>

參數說明:

  • bundle_id:應用程式的 Bundle Identifier(例如 com.microsoft.VSCode
  • uti_or_extension:UTI(Uniform Type Identifier)或副檔名
  • role:角色類型
    • all:所有角色
    • viewer:檢視器
    • editor:編輯器
    • shell:Shell

實用範例

將所有 .txt 檔案預設用 VS Code 開啟:

1
duti -s com.microsoft.VSCode .txt all

將所有 .md 檔案預設用 VS Code 開啟:

1
duti -s com.microsoft.VSCode .md all

設定 .json 檔案:

1
duti -s com.microsoft.VSCode .json all

使用設定檔批次設定

建立一個設定檔 ~/.duti

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 文字檔案
com.microsoft.VSCode .txt all
com.microsoft.VSCode .md all
com.microsoft.VSCode .json all
com.microsoft.VSCode .yaml all
com.microsoft.VSCode .yml all
com.microsoft.VSCode .sh all
com.microsoft.VSCode .zsh all

# 程式碼檔案
com.microsoft.VSCode .js all
com.microsoft.VSCode .ts all
com.microsoft.VSCode .py all
com.microsoft.VSCode .go all
com.microsoft.VSCode .rs all

# 網頁檔案
com.microsoft.VSCode .html all
com.microsoft.VSCode .css all

套用設定檔:

1
duti ~/.duti

查詢應用程式的 Bundle ID

可以使用以下指令查詢應用程式的 Bundle Identifier:

1
2
osascript -e 'id of app "Visual Studio Code"'
# 輸出:com.microsoft.VSCode

或使用 mdls 指令:

1
2
mdls -name kMDItemCFBundleIdentifier /Applications/Safari.app
# 輸出:kMDItemCFBundleIdentifier = "com.apple.Safari"

常見的 Bundle ID

應用程式 Bundle ID
VS Code com.microsoft.VSCode
Sublime Text com.sublimetext.4
Safari com.apple.Safari
Chrome com.google.Chrome
Firefox org.mozilla.firefox
Preview com.apple.Preview
Finder com.apple.finder

搭配 dotfiles 管理

將 duti 設定加入你的 dotfiles 安裝腳本中,可以在新機器上快速還原預設應用程式設定:

1
2
3
4
5
6
7
#!/bin/bash

# install.sh
brew install duti

# 套用預設應用程式設定
duti ~/.duti

總結

duti 是一個簡單但實用的工具,特別適合:

  • 經常重灌系統或換新電腦的使用者
  • 想要自動化 macOS 設定的開發者
  • 管理多台 Mac 的系統管理員

透過 duti,你可以將預設應用程式設定納入版本控制,輕鬆在不同機器間同步設定。

參考資源