直接通过终端命令可立即启用“请勿打扰”模式:先用defaults写入配置,再更新时间戳触发ui刷新,最后killall notificationcenter强制生效;也可用applescript或自定义shell函数实现一键开关。

如果你正在使用Mac终端远程管理服务器、批量部署脚本或编写自动化任务,需要在不触碰图形界面的前提下立即屏蔽所有通知干扰,那么直接通过终端命令开启“请勿打扰”模式就是最底层、最可靠的方案——它绕过GUI进程,直接写入系统偏好设置,且与菜单栏图标、控制中心状态完全同步。
用defaults命令即时启用勿扰模式
打开“终端”应用,输入以下命令并回车:
defaults write com.apple.notificationcenterui doNotDisturb -boolean true
这条命令会立刻将勿扰模式设为开启状态,但此时系统UI尚未刷新。必须紧接着执行刷新操作,否则菜单栏不会显示月牙图标,通知也不会真正静音。
defaults write com.apple.notificationcenterui doNotDisturbDate -date "`date -u +'%Y-%m-%d %H:%M:%S'`"
这一步强制通知中心重载时间戳,触发UI实时更新。屏幕右上角会闪现“勿扰模式已开启”提示,状态栏同步出现月牙标识。
killall NotificationCenter
最后执行此命令,强制重启通知中心守护进程。这是【不可跳过的一步】,否则新设置仅存于配置文件,实际通知仍会弹出。
用AppleScript实现一键开关(兼容性更强)
方法一:启用勿扰模式
osascript -e 'tell application "System Events" to tell appearance preferences to set properties of notification center to {do not disturb:true}'
该脚本调用系统事件接口,兼容macOS Ventura至Sequoia全版本,即使defaults命令在某些M系列芯片Mac上偶发失效,此方式依然稳定生效。
方法二:关闭勿扰模式
osascript -e 'tell application "System Events" to tell appearance preferences to set properties of notification center to {do not disturb:false}'
注意:若执行后无反应,请先确认“系统设置 → 隐私与安全性 → 自动化”中已授权“终端”对“系统事件”的控制权限。
创建可重复调用的shell函数
第一步:编辑当前用户的shell配置文件
在终端中运行:【nano ~/.zshrc】(如使用bash则为~/.bash_profile)
第二步:在文件末尾粘贴以下函数定义:
dnd-on() {
defaults write com.apple.notificationcenterui doNotDisturb -boolean true && \
defaults write com.apple.notificationcenterui doNotDisturbDate -date "`date -u +'%Y-%m-%d %H:%M:%S'`" && \
killall NotificationCenter
}
dnd-off() {
defaults write com.apple.notificationcenterui doNotDisturb -boolean false && \
defaults write com.apple.notificationcenterui doNotDisturbDate -date "`date -u +'%Y-%m-%d %H:%M:%S'`" && \
killall NotificationCenter
}
第三步:保存并退出(Ctrl+O → Enter → Ctrl+X),然后执行 source ~/.zshrc 使函数立即生效。
此后只需在任意终端窗口输入 dnd-on 或 dnd-off,即可秒级切换状态。











