Sub topic 11
Calling shell scripts from a shortcut
This chapter covers the Run Shell Script action. It lets a shortcut hand work to a command-line tool and read the result back. It assumes you can build a multi-step shortcut and use variables, and that you understand Shortcut Input and basic content types. You should also know how to open Terminal and run a command. The shortcuts command-line tool is covered in the next chapter.
Why use a shell script in a shortcut
Most tasks fit the built-in actions. Some do not: filtering text with a regular expression, counting bytes, calling a tool such as curl or jq, or reusing a script you already trust. In those cases, one Run Shell Script action can replace a long chain of actions.
A shell script is a short program that macOS runs through a command interpreter called a shell. The Run Shell Script action is available only in Shortcuts on the Mac, not on iPhone or iPad.
Anatomy of the Run Shell Script action
Search for "Run Shell Script" in the action library and add it to your shortcut. The action has these parts:
| Part | What it controls |
|---|---|
| Shell | The interpreter, such as zsh, bash or sh. zsh is the macOS default. |
| Script text | The commands to run. |
| Input | A variable or the previous action's output, which the script receives. |
| Pass Input | Whether the input arrives on stdin or as arguments. |
| Run as Administrator | Whether the script runs with elevated rights. Leave this off unless you have a specific need. |
The action's output is whatever the script writes to standard output (stdout). The output is Text. Any action after the script can use it, either through the previous-output connection or as a magic variable.
Choosing between stdin and arguments
The Pass Input setting decides how the script sees its input. Choose it by the kind of data you have.
- to stdin suits text. The script reads the input as a stream, the way a filter such as
tr,sortorgrepdoes. - as arguments suits lists of items, especially files. Each item becomes one argument. For files, each argument is a file path.
Example: filter text through stdin
Set Pass Input to "to stdin" and use this script. It converts the incoming text to uppercase and returns it as the action's output.
tr '[:lower:]' '[:upper:]'To build the shortcut, add Ask for Input (type Text), then Run Shell Script with the input set to Provided Input, then Show Result. Typing quarterly report shows QUARTERLY REPORT.
You can check the script in Terminal before you put it in the action. This is the same command with the input piped in:
printf 'quarterly report\n' | tr '[:lower:]' '[:upper:]'Example: handle files through arguments
Set Pass Input to "as arguments". Then set the shortcut to accept Files, either with Shortcut Input from Finder or with a Select File action. This script prints the size in bytes of each file the shortcut received:
for f in "$@"; do
wc -c < "$f"
done"$@" expands to every argument, and the quotes keep a path with spaces in one piece. The < "$f" redirect makes wc print only the number, with no file name.
The output is one line of text per file. To use the numbers later, add Split Text (by New Lines) after the script. Each line then becomes a separate item, and a Repeat with Each loop can process them.
Quoting and spaces
File paths on a Mac often contain spaces, as in ~/Documents/Q3 Report.pdf. An unquoted $f splits that path into two words and the command fails or acts on the wrong file. Always wrap variables in double quotes: "$f", "$1", "$@".
Never build a command by pasting untrusted text into it. If a shortcut accepts text from a person or a web page and you insert it into the script text itself as a magic variable, the text becomes part of the script. A value such as x; rm -r ~/something would then run as a command. Pass the data through stdin or arguments instead, where the shell treats it as data.
The environment the script runs in
A script run from a shortcut does not behave exactly like one typed in Terminal. Three differences cause most surprises.
- PATH is minimal. Your login configuration (
~/.zprofile,~/.zshrc) is usually not loaded. Tools installed with Homebrew, which live in/opt/homebrew/binon Apple silicon Macs, may report "command not found". Either call the tool by its full path or set PATH at the top of the script. - The working directory is not your project folder. Do not rely on relative paths. Use absolute paths, or change directory explicitly with
cd. - Privacy protection applies. macOS asks for permission when Shortcuts reads protected locations such as Desktop, Documents or Downloads. If a script cannot read a file you can see in Finder, check System Settings under Privacy & Security.
This script sets PATH and checks that the tool exists before using it:
export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"
if ! command -v jq >/dev/null 2>&1; then
echo "jq is not installed"
exit 1
fi
jq -r '.name'Set Pass Input to "to stdin" and feed it JSON text. The script prints the name field.
Returning structured data
The output is plain Text, but you can return structured data by printing JSON and parsing it in the shortcut. Add Get Dictionary from Input after the script. Then use Get Dictionary Value to pull out individual keys.
This script reports the number of lines and words in the input:
lines=$(wc -l | tr -d ' ')
printf '{"lines": %s}\n' "$lines"Here wc -l counts newline characters on stdin, and tr -d ' ' removes the padding spaces that macOS wc adds. With stdin input of three lines, the output is {"lines": 3}. Get Dictionary from Input turns that into a dictionary, and Get Dictionary Value for lines returns 3.
Keep the script's output free of extra text. A stray echo "starting..." makes the output invalid JSON, and the dictionary step fails.
Errors and debugging
Only stdout comes back as the action's result. Error messages go to standard error (stderr), which the shortcut does not show you. A script can therefore fail while the result looks empty. Use these habits to find the cause:
- Test in Terminal first. Run the script with realistic input before you paste it into the action.
- Merge stderr into stdout while debugging. Add
exec 2>&1as the first line of the script. Error messages then appear in the Show Result output. - Show intermediate output. Put a Show Result action right after the script, and look at the exact text it returns, including blank lines.
- Check exit codes deliberately. A script ends with the exit code of its last command. Use
exit 1in your own error branches andset -eif you want the script to stop at the first failed command. How the shortcut reports a non-zero exit code can vary, so check the behavior on your macOS version rather than assuming it.
For the step-by-step run mode and result inspection of the editor, see the debugging chapter. The same tools work on this action.
Common errors and their usual causes:
| Symptom | Likely cause |
|---|---|
| `command not found` | PATH is minimal. Use a full path or set PATH in the script. |
| Output is empty | The error went to stderr, or the input was passed the wrong way. |
| Only part of a file name is used | An unquoted variable split a path at a space. |
| Numbers have leading spaces | macOS `wc` pads its output. Strip it with `tr -d ' '`. |
| Operation not permitted | A privacy protection blocked a protected folder. |
Working with the output in the next steps
The returned Text behaves like any other text in a shortcut.
- A single value works directly in If conditions, Show Result and Set Variable.
- Multiple lines need Split Text with New Lines to become a list.
- A trailing newline is normal. If it affects a comparison, trim it in the script with
printf '%s' "$value"instead ofecho. - Numbers come back as text. Shortcuts converts text to a number when an action such as Calculate or a numeric If comparison needs one.
Putting it together: a small project
This shortcut reports the total size of selected files and runs from Finder.
- Create a shortcut and enable Use as Quick Action in its details. Set it to receive Files.
- Add Run Shell Script with Pass Input set to "as arguments" and Input set to Shortcut Input.
- Use a script that sums the sizes:
total=0
for f in "$@"; do
size=$(wc -c < "$f" | tr -d ' ')
total=$((total + size))
done
echo "$total"- Add Show Result and use the script's output.
Select a few files in Finder, right-click, choose Quick Actions, and pick the shortcut. It shows the combined byte count. If it shows 0, check that Pass Input is set to "as arguments" and that the shortcut really receives files.
Security and sharing
A shell script has the same access to your files as you do. When you import a shortcut that contains a Run Shell Script action, read the script before you run it. When you share your own shortcut, review what the script touches. The sharing chapter covers permission review in more detail.
Exercise
A Run Shell Script action is set to "as arguments" and runs for f in $@; do wc -c < $f; done. It works for a.txt but fails for My Notes.txt. What is wrong, and what is the corrected script?
Show answer
The variables are unquoted, so the shell splits My Notes.txt into two words, My and Notes.txt. Quote them: for f in "$@"; do wc -c < "$f"; done.
Exercise
Your script uses jq, which you installed with Homebrew. It works in Terminal but the shortcut reports command not found. Give the cause and one fix.
Show answer
A shortcut's shell has a minimal PATH and does not load your login profile, so /opt/homebrew/bin is not searched. Fix it by calling /opt/homebrew/bin/jq by its full path, or by adding export PATH="/opt/homebrew/bin:$PATH" at the top of the script.