macOS系统的脚本工具osascript

1. 引言

“Every time I get a script it’s a matter of trying to know what I could do with it. I see colors, imagery. It has to have a smell. It’s like falling in love. You can’t give a reason why” - Paul Newman

“Mac OS X is a rock-solid system that’s beautifully designed. I much prefer it to Linux” - Bill Joy

macOS系统的脚本工具 osascript 能够在终端命令行执行一些操作。

基本语法:

osascript [-l language] [-e command] [-s flags] [programfile]

2. 实例

# 弹出提醒
osascript -e 'display alert "上班💼时间到,该打卡了。"'
# Open or switch to Safari
# 打开或切换到 Safari浏览器
osascript -e 'tell app "Safari" to activate'
# Close safari
# 关闭 safari
osascript -e 'quit app "safari.app"'
osascript -e ‘tell application “safari” to quit’
# Empty the trash
# 清空垃圾桶
osascript -e 'tell application "Finder" to empty trash'
# Set the output volume to 50%
# 设置音量🔊为50%
sudo osascript -e 'set volume output volume 50'
# Input volume and Alert volume can also be set from 0 to 100%:
# 设置音量🔊
sudo osascript -e 'set volume input volume 40'
sudo osascript -e 'set volume alert volume 75'
# Mute the output volume (True/False)
# 是否静音🔇
osascript -e 'set volume output muted TRUE'
# Toggle volume muting
# 切换音量静音
osascript -e 'set volume output muted not (output muted of (get volume settings))'
# Toggle system theme
# 切换系统主题—黑色模式
osascript -e 'tell application "System Events" to tell appearance preferences to set dark mode to not dark mode'
# Shut down without asking for confirmation
# 关闭而不询问确认
osascript -e 'tell app "System Events" to shut down'
# Restart without asking for confirmation
# 重启而不询问确认
osascript -e 'tell app "System Events" to restart'

3. 延伸阅读