
AppleScript는 Apple에서 제공하는 다소 생소한 스크립팅 언어지만, 프로그래밍 경험이 많지 않은 초보자도 충분히 활용할 수 있는 강력한 도구입니다. 귀찮은 반복 작업을 대신 처리해 주는 몇 가지 유용한 AppleScript만 있으면 생산성을 크게 높이고 단조로운 업무를 자동화할 수 있습니다.
AppleScript란 무엇인가?

AppleScript는 Finder, 음악(Music), QuickTime, Mail 등 대부분의 Mac 애플리케이션과 상호작용할 수 있습니다. Automator를 사용해 본 경험이 있다면, AppleScript는 그보다 진입 장벽은 높지만 훨씬 세밀한 제어가 가능한 '파워 유저용' 도구라고 이해하면 됩니다.
1. 숨김 파일 표시 전환
아래 코드를 애플리케이션 형태로 저장하면, 클릭 한 번으로 Finder의 숨김 파일을 보이거나 숨길 수 있는 토글 앱이 완성됩니다.
set newHiddenState to "YES"
try
set oldHiddenState to do shell script "defaults read com.apple.finder AppleShowAllFiles"
if oldHiddenState is in {"1", "YES"} then
set newHiddenState to "NO"
end if
end try
do shell script "defaults write com.apple.finder AppleShowAllFiles " & newHiddenState
do shell script "killAll Finder"
2. 파일 일괄 이름 변경
이 스크립트는 사용자에게 새 파일 이름을 입력받은 뒤, 선택한 모든 파일에 해당 문자열과 증가하는 일련번호를 붙여 자동으로 이름을 바꿔 줍니다. 1부터 10까지의 파일에는 나중에 정렬하기 좋도록 앞에 0을 추가해 주는 세심한 배려도 담겨 있습니다.
-- This code comes from https://gist.github.com/oliveratgithub/
-- Open in AppleScript Editor and save as Application
-- ------------------------------------------------------------
--this is required to break the filename into pieces (separate name and extension)
set text item delimiters to "."
tell application "Finder"
set all_files to every item of (choose file with prompt "Choose the Files you'd like to rename:" with multiple selections allowed) as list
display dialog "New file name:" default answer ""
set new_name to text returned of result
--now we start looping through all selected files. 'index' is our counter that we initially set to 1 and then count up with every file.
--the 'index' number is of course required for the sequential renaming of our files!
repeat with index from 1 to the count of all_files
--using our index, we select the appropriate file from our list
set this_file to item index of all_files
set file_name_count to text items of (get name of this_file)
--if the index number is lower than 10, we will add a preceding "0" for a proper filename sorting later
if index is less than 10 then
set index_prefix to "0"
else
set index_prefix to ""
end if
--
--lets check if the current file from our list (based on index-number) has even any file-extension
if number of file_name_count is 1 then
--file_name-count = 1 means, we extracted only 1 text-string from the full file name. So there is no file-extension present.
set file_extension to ""
else
--yup, we are currently processing a file that has a file-extension
--we have to re-add the original file-extension after changing the name of the file!
set file_extension to "." & item -1 of file_name_count
end if
--let's rename our file, add the sequential number from 'index' and add the file-extension to it
set the name of this_file to new_name & index_prefix & index & file_extension as string
end repeat
--congratulations for successfully accomplishing the batch renaming task :)
display alert "All done! Renamed " & index & " files with '" & new_name & "' for you. Have a great day! :)"
end tell
3. 이미지를 백분율(%)로 크기 조절
이 스크립트는 선택한 이미지를 원본 크기의 50%로 축소한 뒤 바탕화면에 저장합니다.
-- Prompt for an image
set theImageFile to choose file of type "public.image" with prompt "Please select an image:"
-- Locate an output folder
set theOutputFolder to (path to desktop folder as string)
-- Launch Image Events
tell application "Image Events"
launch
-- Open the image
set theImage to open theImageFile
tell theImage
-- Determine a save name for the image
set theName to name
set theSaveName to "smlr-" & theName
-- Scale the image by 50%
scale by factor 0.5
-- Save the image to the output folder, using the save name
save as file type in (theOutputFolder & theSaveName)
-- Close the image
close
end tell
end tell
4. 이미지를 픽셀 너비 기준으로 크기 조절
앞선 스크립트와 구조가 비슷하지만, 백분율 대신 원하는 픽셀 너비를 직접 입력받아 그 값에 맞춰 이미지 크기를 조절합니다. 새 파일 이름 앞에는 설정한 픽셀 너비가 함께 붙기 때문에, 어떤 크기로 저장했는지 한눈에 확인할 수 있습니다.
-- Prompt for an image
set theImageFile to choose file of type "public.image" with prompt "Please select an image:"
set dialogResult to (display dialog "Enter desired pixel width:" default answer "") try set pixelWidth to (text returned of dialogResult) as integer end try
-- Locate an output folder
set theOutputFolder to (path to desktop folder as string)
-- Launch Image Events
tell application "Image Events"
launch
-- Open the image
set theImage to open theImageFile
tell theImage
-- Determine a save name for the image
set theName to name
set theSaveName to (pixelWidth as text) & "-px-" & theName
-- Scale the image to pixelWidth
scale to size pixelWidth
-- Save the image to the output folder, using the save name
save as file type in (theOutputFolder & theSaveName)
-- Close the image
close
end tell
end tell
5. 선택한 폴더를 지정 위치로 백업
이 간단한 스크립트는 선택한 폴더를 지정한 목적지로 그대로 복제해 줍니다. 여러 단계를 거쳐야 하는 드래그 앤 드롭 복사 과정을 훨씬 간편하게 만들어 주므로, 주기적으로 백업이 필요한 경우 특히 유용합니다.
set backupTarget to (choose folder with prompt "Select a Backup Target")
set backupDestination to (choose folder with prompt "Select a Backup Destination")
tell application "Finder"
duplicate folder backupTarget to folder backupDestination
end tell
마무리
AppleScript에 대해 더 깊이 알고 싶다면 Apple의 공식 문서를 참고하는 것이 좋습니다. 초보자에게 좀 더 친숙한 설명을 원한다면 MacOSXAutomation.com을 방문해 보세요. 위 스크립트들은 macOS의 '스크립트 편집기(AppleScript Editor)'에 붙여넣은 뒤 애플리케이션 형식으로 저장하면 바로 사용할 수 있습니다.