Skip to main content

Run Shell Script on Selected Text on Mac

· 2 min read
gityeop
Creator of OnText

OnText can run a shell script with the text you selected in the current Mac app. This is useful when a small command is faster than copying text into Terminal, running a script, then pasting the result back.

The workflow is: select text, press F2, then trigger your shell script action.

Basic Shell Action

Create a Shell Script action in OnText and read the selected text from the quoted ONTEXT_TEXT environment variable:

printf '%s' "$ONTEXT_TEXT" | tr '[:lower:]' '[:upper:]' | pbcopy

This copies an uppercase version of the selected text to the clipboard. Keep the variable expansion in double quotes so spaces and special characters stay part of the selected text.

Replace Text After Processing

Add the {paste} placeholder when you want to process text and paste it back:

printf '%s' "$ONTEXT_TEXT" | tr '[:lower:]' '[:upper:]' | pbcopy && {paste}

The command transforms the selection, writes it to the clipboard, then uses {paste} to paste the result.

Selected Text and Other Inputs

Shell actions receive user-controlled values through quoted environment variables:

  • "$ONTEXT_TEXT" for fast selected text capture.
  • "$ONTEXT_TEXT_WITH_COPY" when an app needs copy-based selected text capture.
  • "$ONTEXT_CLIPBOARD" for the current clipboard text.
  • A {prompt} declaration line and "$ONTEXT_PROMPT_1" for extra input.
  • {date}, {time}, and {datetime} for timestamped workflows.

Do not insert selected text, clipboard text, or prompt input directly into Shell command source. OnText offers to migrate older placeholder-based Shell actions when they run.

Read the placeholders guide before building scripts that modify text in place.

Good Use Cases

Shell script actions are useful for:

  • Formatting identifiers such as snake_case or CONSTANT_CASE.
  • Cleaning whitespace or line breaks.
  • Sending selected text to a local command-line tool.
  • Building small clipboard transformations.
  • Combining selected text with prompts or dates.

For more examples, see Shell Scripts and Custom Actions.