DEV Community

Ahmed Musallam
Ahmed Musallam

Posted on

6 1

How to add a "run script" context menu item in macOs

I usually write a shell script file for everything... so I don't have to remember long a$$ commands, especially for running servers or starting builds. It just makes everything easier.

I usually use "New Terminal Tab at Folder" service to, you guessed it, cd into that folder then run my shell script ./run.sh

New Terminal Tab at Folder

You might be thinking: "well, you can just double click it", yeah, I can, but I usually reserve double clicking for when I need to "edit" the shell script, not when I need to "run" it. Because I am frequently editing shell scripts.

So I thought, what if I add a context menu item "Run Script". So I can right-click a file then click "Run Script" and it will open a terminal and run my script for me.

run script

googled 'round, didn't quite find something like that, so I created it! Here is how:

  1. Open Automator
  2. Choose Service
  3. Drag the Run AppleScript action into the workflow
  4. add code below
  5. Save the workflow as run script
  6. Enjoy!


tell application "Finder"
    # Get the directory of the selected file, store it in "selDir"
    set selDir to POSIX path of (parent of first item of (get selection as alias list) as alias)
    # Get the path of the selected file, store it in "selPath"
    set selPath to POSIX path of (selection as text)
    # Optional commands to show dialog, for debugging puposes.
    # display dialog selDir as text
    # display dialog selPath as text
end tell

tell application "Terminal"
    # Open terminal, cd to selected file directory, then run te file.
    do script "cd " & selDir & " && " & selPath
end tell


Enter fullscreen mode Exit fullscreen mode

And now I realized that I've spent about an hour and a half learning some AppleScript when I should have been working on my side project... #MySideProjectsHaveSideProjects 😅

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (2)

Collapse
 
vivekkodira profile image
Vivek Kodira •

Thank you :)

Collapse
 
rowild profile image
Robert Wildling •

How would I get the current folder instead of the parent folder?

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs