简体   繁体   中英

Invoke copy & paste commands from terminal

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.

osascript -e 'try
    set old to the clipboard
end try
try
    delay 0.3
    tell application "System Events" to keystroke "c" using command down
    delay 0.2
    set text item delimiters to linefeed
    set input to (paragraphs of (the clipboard as text)) as text
    set the clipboard to do shell script "shopt -u xpg_echo; echo -n " & quoted form of input & " | rev" without altering line endings
    tell application "System Events" to keystroke "v" using command down
    delay 0.05
end try
try
    set the clipboard to old
end try'

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 clipboard would sometimes be set to old before the text would get pasted.

the clipboard as text and do shell script convert line endings to carriage returns by default. shopt -u xpg_echo is needed because the echo in sh interprets backslashes inside single quotes by default. If the input is longer than getconf ARG_MAX bytes, you can't use echo and have to either write it to a temporary file or use pbpaste .

pbpaste and pbcopy replace non-ASCII characters with question marks by default in the environment used by do shell script You can prevent that by setting LC_CTYPE to UTF-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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM