Is there a way to execute global hotkey using the command line?

0

OS: OS X 10.9.1 Mavericks

Is it possible to execute any global hotkeys from the command line?

For example, if I wanted to copy and paste, is there a command to let me type the exact hotkey and execute it?

Like this (This command is just for an example, doesn't actually exists):

hotkey "ctrl+c"
hotkey "ctrl+v"

I know there's already a command to copy and paste "pbpaste" and "pbcopy", I was just using copy and paste as an example.

This would be very useful to execute commands that could be very lengthy on the command line. If you wanted to lock the computer on the command line you'd have to do something like:

/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend

If there's a command to execute hotkeys all you had to do is:

hotkey "ctrl+shift+eject"

Timber

Posted 2014-02-17T05:01:13.750

Reputation: 107

Answers

1

AppleScript has the keystroke and key code commands:

osascript -e 'tell app "System Events" to keystroke "a" using command down'

osascript -e 'tell app "System Events" to key code 126 using {control down, shift down}'

There is no key code for the eject key though.

Lri

Posted 2014-02-17T05:01:13.750

Reputation: 34 501

Great answer! But is there another way to do this without using AppleScript? If there are no none, then I will accept your answer. Thank you for taking the time to write that, I appreciate it. – Timber – 2014-02-20T03:19:23.653

1@TimothyOnggowasito, If you're expecting to control user input (keyboard commands) there's really no other way in OS X that I'm aware of; if there was any other way Lauri Ranta might very well be the only person who would know. – l'L'l – 2014-02-20T22:35:31.073

@LauriRanta Looks like there are no other way, I will accept your answer and award this answer with bounty :). Thank your very very much! – Timber – 2014-02-23T05:30:21.057

2

You can combine Lauri's AppleScript with a hotkey-based system (Quicksilver, Keyboard Maestro, etc.) to create hotkeys for running complex commands. But "hotkeys" are normally part of the GUI environment, not the CLI. They don't appear in the Terminal, although their results might if you are using Command-V to paste in text.

Have you looked into shell aliases? You could create an alias called "lock" that maps to "/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend". It's not a (GUI) hotkey, but since you asked about the CLI in particular, perhaps this will help.

jimtut

Posted 2014-02-17T05:01:13.750

Reputation: 832