Skip to content
Advertisement

How can execute a shell script from spotlight on macOS passing a first command line argument?

I have written a python program that needs a first command line argument to run from the Terminal. The program can be used to copy a text to the clipboard when it is run with a certain keyword.

~ python3 mclip.py 'agree'

This use case is just an exercise to understand, how I can run a batch file on macOS (or shell script in macOS terminology).

I have created the following shell script and saved it as mclip.command:

#!/usr/bin/env bash
python3 /Users/Andrea_5K/mclip.py

My idea is to execute my shell script from the spotlight input window, passing the argument ‘agree’. How can I do that?

On windows the batch file would look like that (mclip.bat):

@py.exe C:path_to_my_filemclip.py %*
@pause

I can press WIN-R and type mclip *argument* to run the program. But how can I do the same on a Mac? I cannot type mclip agree in spotlight, that doesn’t work like in WIN-R.

#! python3
# mclip.py - A multi-clipboard program.

TEXT = {
    'agree': """Yes, I agree. That sounds fine to me.""",
    'busy': """Sorry, can we do this later this week or next week?""",
    'upsell': """Would you consider making this a monthly donation?""",
}

import sys, pyperclip
if len(sys.argv) < 2:
    print('Usage: python mclip.py [keyphrase] - copy phrase text')
    sys.exit()

keyphrase = sys.argv[1] # first command line arg is the keyphrase

if keyphrase in TEXT:
    pyperclip.copy(TEXT[keyphrase])
    print('Text for ' + keyphrase + ' copied to clipboard.')
else:
    print('There is no text for ' + keyphrase)

Advertisement

Answer

Assume the shell script (mapIt.command) is:

#!/usr/bin/env bash
python3 /path/to/my/pythonScript.py $@ 

The $@ is interpreted as a list of command line arguments.

I can run the shell script in the MacOS Terminal like that:

sh mapIt.command Streetname Number City

The command line arguments Streetname Number City are forwarded to the python script.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement