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"

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.

  • 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 Feb 20 '14 at 3:19
  • 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 Feb 20 '14 at 22:35
  • @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 Feb 23 '14 at 5:30

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.