osascript是在macOS上执行AppleScript的命令行工具

常用命令

在桌面显示通知

osascript -e ' display notification "通知内容" with title "标题" subtitle "子标题" '

获取当前IP地址

osascript -e "IPv4 address of (system info)"

AppleScript 简介

  • 编辑器 Script Editor.app
  • 保存脚本后缀 scpt
  • 命令行执行脚本 osascript test.scpt

变量

set width to 8
set height to 9
set area to width * height
# 常用的运算符有:+、-、*、/、^、 对的,加减乘除乘方

set myString to "我的故事"

动作

beep 2
# 哔两次

display dialog myString
# 弹出框

set theLength to the length of "Neal"
# 获取字符串的长度

set strToNumber to "16" as number
set numToStr to 12 as string
# 类型转换

set exampleList to {1,2,3,"hahah",9}
#定义数组,数组元素的index从1开始

set addToBegin to {"winter"}
set addToEnd to {"summer", "autumn"}
set currentList to {"spring"}
set modifiedList to addToBegin & currentList & addToEnd
# 数组拼接

set testList to {"Neal", "haha"}
set item 2 of testList to "yang"
get testList
# 变更数组元素。输出 {"Neal", "yang"}

set myList to {"neal", "haha"}
set valueOfLastItem to item -1 of myList
# 通过index获取数组元素,index为负数代表从右往左取。

set myList to {"a", "b", "c", "d", "e", "f"}
set shortList to items 2 through 5 of myList
# 通过index的区间取多个数组元素

set reversedList to reverse of {2, 3, 4, 6, 7}
# reverse数组倒序

set theListLength to the count of {"ds", 1, 2, 3}
# count或length获取数组长度

set x to some item of {1, 2, 3, 4, 5, 7, 7, 6, 5}
# some随机获取数组元素

set itemized to every character of "Nealyang"
get itemized
# every character of 将字符串转成字符数组

set myString to "neal's personal website is www.nealyang.cn"
set oldDelimiters to AppleScript's text item delimiters #保持原单词分割符
set AppleScript's text item delimiters to " " #定义单词分割符为空格
set myList to every text item of myString
set AppleScript's text item delimiters to oldDelimiters #恢复原单词分割符
get myList
# every text item of 将字符串用分割符转成字符串数组

set man to {name:"yang", age:13}
set manName to name of man
get manName
# 对象的定义和取值

set stringToBeDisplayed to "Neal is pretty boy"
set tempVar to display dialog stringToBeDisplayed buttons {"So,so", "Don't know", "yes"}
set theButtonPressed to button returned of tempVar
display dialog "You pressed the following button " & theButtonPressed
# 弹出框取得点击的按钮

条件判断

set ageEntered to 73
set myAge to 24
if ageEntered is myAge then
    display dialog "You are as old as I am "
else
    beep
end if

错误处理

try
    set a to 1 / 0
on error the errMessage number the errNumber
    display dialog "Error: " & errNumber & "." & errMessage buttons {"OK"}
end try

定义函数

on fun1(info)
    display dialog info buttons {"Close"}
end fun1
# on 定义函数

fun1("啥")
# 调用函数

遍历

set theList to {"a", "b", "c"}
repeat with c in theList
	display dialog c buttons {"Close"}
end repeat

操作应用程序

tell application "Finder"
    empty the trash
end tell
# tell 操作应用程序