Skip to content

Instantly share code, notes, and snippets.

@nayanseth
Last active June 20, 2023 03:58
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save nayanseth/c18931e0777579467a12 to your computer and use it in GitHub Desktop.
Save nayanseth/c18931e0777579467a12 to your computer and use it in GitHub Desktop.
Basics of AppleScript
(*
Script - Comments
@author - Nayan Seth
© Tech Barrack Solutions Pvt Ltd
*)
--This is a single line comment
#This is a comment too but still single line
(*
This is a
multi
line
comment
*)
#Comments are ignored by AppleScript. Its used for explaining something.
(*
Script - Say Command
@author - Nayan Seth
© Tech Barrack Solutions Pvt Ltd
*)
say "Hi I am a Mac"
say "Hi I am a Mac" using "Zarvox"
(*
Script - Beep Command
@author - Nayan Seth
© Tech Barrack Solutions Pvt Ltd
*)
beep --beeps 1 time
beep 5 --beeps 5 times
(*
Script - Tell Command
@author - Nayan Seth
© Tech Barrack Solutions Pvt Ltd
*)
tell application "Finder"
empty the trash
open the startup disk
beep 10
say "Hi. how are you doing today?" using "Victoria"
end tell
tell application "Finder"
empty the trash
open the startup disk
end tell
# The commands below can be used inside the tell command too
beep 10
say "Hi. how are you doing today?" using "Zarvox"
(*
Script - Variables & Arithmetic
@author - Nayan Seth
© Tech Barrack Solutions Pvt Ltd
*)
--(Program 1) Integers
set x to 5
--(Program 2) Floating Point Numbers
set y to 10.5
--(Program 3) Use variables to create new variable
set pictureWidth to 1920
set pictureHeight to 1080
set resolution to pictureWidth * pictureHeight
(*
Topic - Dialog
@author - Nayan Seth
© Tech Barrack Solutions Pvt Ltd
*)
--(Program 1) Strings and Strings and Strings only
set emptyString to ""
set spaceString to " "
set stringText to "Hello World"
--(Program 2) Display Dialog
display dialog "Hello World" --displaying a dialog with text
--(Program 3) Next up we will see how to use String variables in Dialog
set hello to "Hello World" --creates variable hello
display dialog "hello" --prints hello in dialog and not contents of hello variable
display dialog hello --prints contents of hello variable.
--(Program 4) Now its time to merge strings and display it
set firstName to "Nayan" --variable stores my first name
set lastName to "Seth" --variable stores my last name
set myName to firstName & " " & lastName --variable stores first name and last name
display dialog myName --dialog prints the merged string that is myName
--(Program 5) Length of strings
set strLength to the length of "Nayan" --strLength is equal to the length of "Nayan" that is 5
--(Program 6) Escape Sequences
set exampleString to "Nayan is \"Awesome\"" --adds " in String itself
display dialog exampleString
set exampleString2 to "Nayan is Awesome" -- \t adds tab space. On compiling tab space is added
display dialog exampleString2
--(Program 7) Escape Sequences in Dialog
display dialog "Nayan \\\" Seth"
--(Program 8) Coercion
set input to "15" as number
set numToString to 15 as string
--(Program 9) Dialog with Custom Buttons
display dialog "Yo!!!" buttons {"Click Me", "Don't Click Me", "Test Me"} default button 1
(*
Topic - Lists
@author - Nayan Seth
© Tech Barrack Solutions Pvt Ltd
*)
--(Program 1) Declaring Lists
set myList to {"MacBook Pro", "iPad", "iPhone"} --this will print the list too in result tab
--(Program 2) Print List
get myList
--(Program 3) Merging Lists and Printing the Merged List
set laptop to {"MacBook Pro"}
set tablet to {"iPad"}
set phone to {"iPhone"}
set devices to laptop & tablet & phone
get devices
--(Program 4) Modifying Lists
set seasons to {"summer", "spring", "winter"}
set item 2 of seasons to "monsoon"
get seasons
--(Program 5) Modifying Lists 2nd Method
set buy to {"phone", "usb", "pc"}
set 2nd item of buy to "pen drive"
get buy
--(Program 6) Modifying Lists 3rd Method
set musicList to {"songs", "lyrics", "artists"}
set first item of musicList to "albums"
set last item of musicList to "playlists"
get musicList
--(Program 7) Getting Items From List
set bag to {"books", "assignments"}
set engineering to the last item of bag
--(Program 8) Last Item Minus
set newspaper to {"articles", "author", "advertisements"}
set itemValue to item -1 of newspaper
--(Program 9) Size of List
set college to {"departments", "classes"}
set listSize to the length of college
--(Program 10) Partition of List
set vowels to {"a", "e", "i", "o", "u"}
set letters to items 2 through 4 of vowels
--(Program 11) Reverse a List
set reverseList to reverse of {1, 2, 3}
--(Program 12) Random Value
set randomValue to some item of {"success", "failure", "life", "fun"}
--(Program 13) Coercion
set bank to "money in the bank"
set myBankList to bank as list
--(Program 14) Merging Different Types
set cards to {"deck"}
set cartoon to "dragon ball z"
set playingCards to cartoon & cards
--(Program 15) Merging Different Types & Applying Coercion
set cards to {"deck"}
set cartoon to "dragon ball z"
set playingCards to (cartoon as list) & cards
--(Program 16) Characters
set myLetters to every character of "Nayan Seth"
--(Program 17) Delimiters
set myName to "Nayan Seth"
set oldDelimiters to AppleScript's text item delimiters
set AppleScript's text item delimiters to " "
set studentData to every text item of myName
set AppleScript's text item delimiters to oldDelimiters
get studentData
--(Program 18) Add Custom Delimiters to String
set myData to {"Nayan", "Seth"}
set oldDelimiters to AppleScript's text item delimiters
set AppleScript's text item delimiters to "|"
set myName to myData as string
set AppleScript's text item delimiters to oldDelimiters
get myName
(*
Topic - More on Dialogs
@author - Nayan Seth
© Tech Barrack Solutions Pvt Ltd
*)
--(Program 1) Button Pressed
set myName to "Nayan Seth"
set dialogName to display dialog myName buttons {"Cancel", "Ok"} default button 2
set buttonName to button returned of dialogName
display dialog "You pressed " & buttonName
--(Program 2) User Input
set myName to display dialog "What is your name?" default answer ""
set textValue to text returned of myName
set lengthSize to length of text returned of myName
--(Program 3) Coercion
set myAge to display dialog "What is your age?" default answer ""
set studentAge to text returned of myAge as number
(*
Topic - Records
@author - Nayan Seth
© Tech Barrack Solutions Pvt Ltd
*)
--(Program 1) Declaring Records
set propertyName to {age:20}
--(Program 2) Retrieving Data From Records
set studentData to {myName:"Nayan Seth", myAge:20}
set studentAge to myAge of studentData
--(Program 3) No of Properties in a Record
set studentData to {myName:"Nayan Seth", myAge:20}
set recordSize to count of studentData
--(Program 4) Importing Data From One Record To Another Via Intermediate Variable
set studentData to {myName:"Nayan Seth", myAge:20}
set studentAge to myAge of studentData
set newStudentData to {age:studentAge}
--(Program 5) Importing Data From One Record To Another Directly
set studentData to {myName:"Nayan Seth", myAge:20}
set newStudentData to {age:myAge of studentData}
--(Program 6) Trying to Create Copy
set studentData to {myAge:18}
set copyStudentData to studentData
set myAge of studentData to 20
get copyStudentData
--(Program 7) Copy Command
set studentData to {myAge:18}
copy studentData to copyStudentData
set myAge of studentData to 20
get copyStudentData
(*
Topic - Conditional Statements
@author - Nayan Seth
© Tech Barrack Solutions Pvt Ltd
*)
--(Program 1) Simple Comparisons
30 = 30
"nayan" = "nayan"
--(Program 2) if else
if true then
-- insert actions here
end if
if false then
-- insert actions here
end if
--(Program 3) if condition
set myAge to 20
if myAge is greater than or equal to 18 then
beep
display dialog "You are eligible to Vote"
say "You are eligible to Vote" using "Zarvox"
end if
--(Program 4) if and else
set myAge to 17
if myAge is greater than or equal to 18 then
beep
display dialog "You are eligible to Vote"
say "You are eligible to Vote" using "Zarvox"
else
display dialog "You are not eligible to Vote"
end if
--(Program 5) String Comparison if
set myName to "Nayan Seth"
if myName is equal to "Nayan Seth" then
display dialog "True"
end if
if myName starts with "Nayan" then
beep
end if
if "Nayan" comes before "Seth" then
beep
end if
--(Program 6) Case Sensitive
set singleCharacter to "s"
set myName to "Nayan Seth"
considering case
if myName contains singleCharacter then
beep
else
display dialog "Does not contain " & singleCharacter
end if
end considering
--(Program 7) Ignoring White Space
set fullName to "Naya n Seth"
set myName to "Nayan Seth"
ignoring white space
if myName is equal to fullName then
display dialog "Success"
else
beep
end if
end ignoring
--(Program 8) Ignoring White Space
set fullName to "Naya n Seth"
set myName to "Nayan Seth"
ignoring white space
if myName is equal to fullName then
display dialog "Success"
else
beep
end if
end ignoring
--(Program 9) Dialog Buttons and Actions
display dialog "My Name is Nayan Seth" buttons {"Cancel", "No", "Yes"} default button 3
if the button returned of the result is "Yes" then
say "That is true"
else if button returned of the result is "No" then
say "You clicked the wrong button"
end if
--(Program 10) Dialog Buttons and Actions Using Variables
set temp to display dialog "My Name is Nayan Seth" buttons {"Cancel", "No", "Yes"} default button 3
set buttonName to button returned of temp
if the buttonName is equal to "Yes" then
say "That is true"
else if buttonName is equal to "No" then
say "You clicked the wrong button"
end if
--(Program 11) Records if...else
set studentData to {myName:"Nayan", myAge:20}
if myName of studentData is equal to "Nayan" then
display dialog "Success"
else
beep
end if
--(Program 12) AND
set x to true
set y to true
if x and y then
display dialog "True"
else
display dialog "False"
end if
--(Program 13) OR
set x to true
set y to false
if x or y then
display dialog "True"
else
display dialog "False"
end if
--(Program 14) AND with Different Data Types
set x to true
set y to "xyz"
if x and y = "xyz" then
beep
else
say "False Condition"
end if
(*
Topic - Try
@author - Nayan Seth
© Tech Barrack Solutions Pvt Ltd
*)
--(Program 1) Simple Example
try
beep
set x to 1 / 0
say "I cannot speak this"
end try
say "Hey There"
--(Program 2) Number Exception
set temp to display dialog "Enter Age" default answer ""
set myAge to the text returned of temp
try
set myAge to myAge as number
display dialog myAge
on error
display dialog "Please enter a number"
end try
--(Program 3) Error Message and Error Number
set temp to display dialog "Enter Age" default answer ""
set myAge to the text returned of temp
try
set myAge to myAge as number
display dialog myAge
on error the errorMessage number the errorNumber
display dialog "Error " & errorNumber & " : " & errorMessage
end try
(*
Topic - Files and Folders
@author - Nayan Seth
© Tech Barrack Solutions Pvt Ltd
*)
--(Program 1) Choose a Folder
choose folder
--(Program 2) Open a Folder
tell application "Finder"
open "Macintosh HD:Users:nayan:Desktop"
end tell
--(Program 3) Open a File
tell application "Finder"
open "Macintosh HD:Users:nayan:Desktop:text.rtf"
end tell
--(Program 4) Set Path of File to a Variable
tell application "Finder"
set thePath to file "Macintosh HD:Users:nayan:Desktop:text.rtf"
end tell
--(Program 5) Reference to File
tell application "Finder"
set thePath to a reference to file "Macintosh HD:Users:nayan:Desktop:text.rtf"
end tell
--(Program 6) Move Files
tell application "Finder"
move file "Macintosh HD:Users:nayan:Desktop:text.rtf" to "Macintosh HD:Users:nayan:Downloads:"
end tell
--(Program 7) Alias
set thePath to alias "Macintosh HD:Users:nayan:Desktop:text.rtf"
tell application "Finder"
move file "Macintosh HD:Users:nayan:Desktop:text.rtf" to "Macintosh HD:Users:nayan:Downloads:"
open thePath
end tell
--(Program 8) Move Files to Trash
tell application "Finder"
move file "Macintosh HD:Users:nayan:Desktop:text.rtf" to trash
end tell
(*
Topic - Loops
@author - Nayan Seth
© Tech Barrack Solutions Pvt Ltd
*)
--(Program 1) Creating a Loop
repeat 2 times
say "This is a loop"
end repeat
--(Program 2) Creating a Loop using Variable
set i to 2
repeat i times
-- commands to be repeated
end repeat
--(Program 3) Combining try, if...else and repeat
set temp to display dialog "Enter integer" default answer ""
set i to text returned of temp
try
set i to i as integer
end try
if class of i is integer then
repeat i times
say "Hey this works"
end repeat
else
display dialog "Please enter integer"
end if
--(Program 4) Condition Based Loops
set condition to false
repeat until condition is true
set temp to display dialog "Enter age" default answer ""
set x to text returned of temp
try
set x to x as integer
on error
display dialog "Please enter a number"
end try
if class of x is integer then
set condition to true
if x is greater than or equal to 18 then
say "Eligible to vote"
else
say "Not eligible to vote"
end if
end if
end repeat
--(Program 5) Working with Counters
repeat with counter from 1 to 5
say "I ran " & counter & " kilometers."
end repeat
--(Program 6) Counters Increment
repeat with counter from 1 to 5 by 2
say "I ran " & counter & " kilometers."
end repeat
--(Program 7) List of Folders in a Folder
tell application "Finder"
set folderPath to choose folder "Select Folder"
set folderList to every folder of folderPath
end tell
set actualList to {}
repeat with counter in folderList
set fName to name of counter
set actualList to actualList & fName
end repeat
(*
Topic - Handlers
@author - Nayan Seth
© Tech Barrack Solutions Pvt Ltd
*)
--(Program 1) Creating a Handler
on method1()
display dialog "This handler was executed"
end method1
--(Program 2) Calling a Handler
method1()
--(Program 3) Parametrized Handler
on method2(input) -- parametrized handler
display dialog input
end method2
method2("Hey There. I am Nayan Seth.") -- passing parameters value
--(Program 4) Parametrized Handler With Try, Repeat
on area(radius) -- parametrized handler
set circleArea to pi * (radius ^ 2)
display dialog "Area of Circle is " & circleArea
end area
set condition to false
repeat until condition is true
set temp to display dialog "Enter radius of Circle" default answer ""
set r to text returned of temp
try
set r to r as integer
on error
display dialog "Enter a valid number"
end try
if class of r is integer then
set condition to true
area(r)
end if
end repeat
--(Program 5) Return Value from Handler
on large(a, b) -- parametrized handler
if a > b then
return a -- returns a value
else
return b -- returns a value
end if
end large
set largest to large(15, 10) -- largest stores return value of handler large
--(Program 6) Return List from Handler
on square(s) -- parametrized handler
set perimeter to 4 * s
set area to s ^ 2
return {area, perimeter} -- returns a list
end square
set squareList to square(5)
--(Program 7) Calling Methods in Tell
on completion()
display dialog "Success"
end completion
tell application "Finder"
empty trash
completion() of me
end tell
@casajake
Copy link

I have your "AppleScript" book in apple books, but parts are unreadable because the text and background are reversed. The rest of my Mac and iBooks aren't dark. Do you have any suggestions or a link to your book elsewhere? Thanks for your help!

@nayanseth
Copy link
Author

I have your "AppleScript" book in apple books, but parts are unreadable because the text and background are reversed. The rest of my Mac and iBooks aren't dark. Do you have any suggestions or a link to your book elsewhere? Thanks for your help!

Check the README.md in https://github.com/nayanseth/applescript

@casajake
Copy link

casajake commented Sep 30, 2020 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment