AppleScript是macOS内置的脚本语言,可以自动化操作应用程序。本文介绍了AppleScript的基本概念、语法和一个简单实战示例。
<br/>
<!--more-->AppleScript是苹果公司推出的一种脚本语言,内置于macOS中,可以直接操作和控制macOS及其应用程序。它是一个实现macOS自动化的强大工具,AppleScript的前身是HyperCard所使用的脚本语言HyperTalk。
与其他脚本语言如Python和JavaScript相比,AppleScript最显著的特点是能够控制其他macOS上的应用程序。通过AppleScript,我们可以完成一些繁琐重复的工作。其语法简单,接近自然语言,就像在和系统对话一样。此外,系统提供了语法查询字典,方便查询语法。
<br/>
按照惯例,用AppleScript写一个Hello World:
display dialog "Hello, world!"
命令行执行:
osascript -e 'display dialog "Hello, world!"'
运行后,系统会弹出“Hello, world!”的弹窗。
<br/>
下面介绍几种常用语法:
AppleScript的语法接近自然语言,例如:
tell application "Safari"
activate
open location "https://qq.com/"
end tell
这告诉Safari启动并打开指定网址。
set qq to "https://qq.com/"
tell application "Safari"
activate
open location qq
end tell
<br/>
if num > 2 then
// ...
else
// ...
end if
<br/>
repeat with num in {1, 2, 3}
display dialog "hello, world"
end repeat
<br/>
可以使用click
命令模拟点击,或keystroke
输入文本。
<br/>
执行以下命令可以展示一条通知:
osascript -e 'display notification "The command finished" with title "Success"'
在.zshrc中定义一个函数:
function notifyResult () {
if [ $? -eq 0 ]; then
osascript -e 'display notification "The command finished" with title "Success"'
else
osascript -e 'display notification "The command failed" with title "Failed"'
fi
}
运行长时间命令时:
some_program; notifyResult
执行完后会收到通知是否执行成功!
可以设置通知音效:
<br/>
源代码:
代码如下:
sys-notify
#!/bin/bash
# 帮助函数
show_help() {
echo "Usage: $0 [Option] [message]"
echo "Show system notification"
echo
echo "Option:"
echo " -h, --help Show help info"
echo " -t, --title TITLE Set notification title (Default: Notify)"
exit 0
}
# 默认值
title="Notify"
# 解析命令行参数
while [[ $# -gt 0 ]]; do
case "$1" in
-h|--help)
show_help
;;
-t|--title)
if [[ -z "$2" ]]; then
echo "错误: --title 需要一个参数" >&2
exit 1
fi
title="$2"
shift 2
;;
*)
# 第一个非选项参数视为消息内容
message="$1"
shift
break
;;
esac
done
# 如果没有提供消息内容,则从标准输入读取
if [[ -z "$message" ]]; then
if [[ -t 0 ]]; then
echo "错误: 没有提供消息内容" >&2
show_help
exit 1
else
message=$(cat)
fi
fi
# 发送通知
case "$(uname -s)" in
Darwin)
# macOS 使用 AppleScript
osascript -e "display notification \"$message\" with title \"$title\""
;;
Linux)
# Linux 使用 notify-send (libnotify)
if command -v notify-send &>/dev/null; then
notify-send "$title" "$message"
else
echo "错误: 未找到 notify-send 命令。请安装 libnotify 包。" >&2
exit 1
fi
;;
*)
echo "错误: 不支持的操作系统" >&2
exit 1
;;
esac
准备:
sys-notify
;chmod +x sys-notify
;使用方法:
sys-notify "操作已完成"
sys-notify -t "操作结果" "操作已完成"
echo "操作已完成" | sys-notify -t "操作结果"
<br/>
源代码:
function notifyResult () {
if [ $? -eq 0 ]; then
osascript -e 'display notification "The command finished" with title "Success"'
else
osascript -e 'display notification "The command failed" with title "Failed"'
fi
}
在运行某些需要比较长时间的程序时,执行以下命令:
some_program; notifyResult
<br/>
AppleScript是一个简单而强大的工具,能自动化macOS操作;
更多内容可参考附录链接;
<br/>
源代码:
官方文档:
参考文章:
<br/>