Is is possible to invoke a copy command (as if the user pressed Cmd+C) from a bash script? Basically I want to write a simple script that I run with a global hotkey and it should take the current selection from the active app, replace something and paste the result. Is this possible?
The best I could come up so far is using pbpaste and pbcopy, but I’d like to automate that if possible.
If you’re just trying to modify a text selection, you could use AppleScript.
The first delay is for releasing modifier keys if the script is run with a shortcut that has other modifier keys than command. The second delay could also be reduced to something like 0.05, but long selections or for example web views often need a longer delay. Without the third delay,
the clipboardwould sometimes be set tooldbefore the text would get pasted.the clipboard as textanddo shell scriptconvert line endings to carriage returns by default.shopt -u xpg_echois needed because theechoinshinterprets backslashes inside single quotes by default. If the input is longer thangetconf ARG_MAXbytes, you can’t useechoand have to either write it to a temporary file or usepbpaste.pbpasteandpbcopyreplace non-ASCII characters with question marks by default in the environment used bydo shell scriptYou can prevent that by settingLC_CTYPEtoUTF-8.Telling System Events to click menu bar items would often be even slower, and it wouldn’t work in applications that don’t have a menu bar or in full screen windows.
Another option would be to create an Automator service. But they also have small delays before they are run. There’s a bug where the shortcuts for services don’t always work until the services menu has been shown once on the menu bar. And the services aren’t available when the frontmost application doesn’t have a menu bar or a services menu.