What is osascript?

Godson PrakasiaGodson Prakasia
2 min read

What is osascript?

osascript is a command-line tool in macOS that lets you run AppleScript (and JavaScript for Automation) scripts directly from the terminal or shell scripts. It interacts with macOS applications and system functions, enabling automation of tasks like controlling apps, dialogs, file operations, and more.


Key Features of osascript

  1. Run AppleScript Code

    • Execute .scpt files or inline scripts.
  2. Control macOS Apps

    • Manipulate apps like Finder, Safari, or Music.
  3. System Automation

    • GUI scripting, dialogs, file operations, etc.
  4. Supports JavaScript (via JXA – JavaScript for Automation).


Basic Usage

1. Run an AppleScript Command

osascript -e 'tell application "Finder" to display dialog "Hello, macOS!"'
  • -e executes inline AppleScript code.

2. Run a Script from a File (.scpt or .applescript)

osascript /path/to/script.scpt

3. Use JavaScript (JXA) Instead of AppleScript

osascript -l JavaScript -e 'Application("Finder").displayDialog("Hello from JS!")'

Common Use Cases

TaskCommand
Open an Apposascript -e 'tell app "Safari" to activate'
Show a Dialogosascript -e 'display dialog "Backup complete!" buttons {"OK"}'
Get Current Track in Musicosascript -e 'tell app "Music" to name of current track'
Set Volumeosascript -e 'set volume output volume 50'
Click a GUI Button(Accessibility)Requires cliclick or UI scripting.

Advanced Examples

1. Get Wi-Fi Network Name

osascript -e 'do shell script "networksetup -getairportnetwork en0 | cut -c 24-"'

2. Open a URL in Safari

osascript -e 'tell app "Safari" to open location "https://google.com"'

3. Batch Rename Files (Finder Automation)

osascript <<EOF
tell application "Finder"
   set filesToRename to every file of folder "Macintosh HD:Users:me:Desktop:Files"
   repeat with aFile in filesToRename
      set name of aFile to "Prefix_" & name of aFile
   end repeat
end tell
EOF

Limitations & Security

  • Permissions Required: Some actions (like UI scripting) need:

      sudo chmod 755 /usr/bin/osascript  # Rarely needed; usually just Privacy settings.
    
  • Grant Terminal Accessibility Access:

    • Go to System Settings > Privacy & Security > Accessibility and add Terminal.

Alternatives

  • Automator (GUI-based automation).

  • Shortcuts (macOS Monterey+).

  • Swift Scripting (for more advanced control).

0
Subscribe to my newsletter

Read articles from Godson Prakasia directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Godson Prakasia
Godson Prakasia