How do I map a terminal command to a function key?

I have a terminal command that can control my external display's brightness. I'm trying to map that command to a key on the keyboard so it works like a "brightness up" and "brightness down" key.

Karabiner doesn't look like it supports mapping keys to terminal commands


Solution 1:

I would use Automator to run a Shell Script and then add a keyboard shortcut to run that.

To do this:

  1. Open Automator
  2. Press commandN (or go to File > New)
  3. Select the Service option and click on the Choose button
  4. Make sure it's set to receive no input in any application
  5. In the leftmost pane, select the Library > Utilities option
  6. In the middle pane, double-click on the Run Shell Script action
  7. Now enter the terminal command in the Run Shell Script window within the right pane
  8. Press commandS (or go to File > Save...)
  9. Give the Service an appropriate name
  10. Click on the Save button
  11. Now go to Apple > System Preferences... > Keyboard
  12. Select the Shortcuts tab
  13. Select Services in the left pane
  14. Find and select the Service you just created in the list on the righthand side
  15. Click on the Add Shortcut button and press the keyboard shortcut you want to use

NOTE: You will need to ensure it's not a shortcut already being used by macOS.

Solution 2:

I am using karabiner-elements to do exactly this on a Dell monitor, you can bind keypresses to shell commands:

{
"title": "F5 to dim, F6 to bright",
"rules": [
    {
        "manipulators": [
            {
              "description": "dim",
              "type": "basic",
              "from": {
                "key_code": "f5"
              },
              "to": [
                {
                    "shell_command": "/usr/local/bin/ddcctl -d 1 -b 1"
                }
              ]
            },
            {
                "description": "bright",
                "type": "basic",
                "from": {
                  "key_code": "f6"
                },
                "to": [
                  {
                      "shell_command": "/usr/local/bin/ddcctl -d 1 -b 100"
                  }
                ]
              }
          ]
    }
]

}

(I have ddctl installed, which lets you control the brightness by passing it a percentage value - https://github.com/kfix/ddcctl )

You can check the docs for writing your Complex Modifications like this one: https://pqrs.org/osx/karabiner/json.html