Running Scripts at Login MacOS
Kyle Parisi

Kyle Parisi @kyleparisi

About: Working on https://buildapart.io, https://fluxion.app in my spare time.

Location:
Newtown, PA
Joined:
Jun 20, 2018

Running Scripts at Login MacOS

Publish Date: May 13 '20
9 4

The Problem

Every time my computer restarts and I try to pull a git repo, I get a credentials error. So I have to open terminal and run:

ssh-add -KA

This command will take your keychain ssh keys and add them to the ssh agent. The -K is not required but if you don't have a passphrase stored for an ssh key already you can enter it now. I don't recall this being a problem in older versions of MacOS but it is a problem now.

The Solution

I decided to make use of the LaunchAgent feature. This feature will run for the current user, at login, either a daemon or one-off scripts. Here is what you need to do to have the above command run at login.

Create the following script

#!/bin/bash

ssh-add -KA

Place the script somewhere you like

mkdir -p ~/scripts/startup
# create script in ^ folder
chmod +x ~/scripts/startup/ssh-add.sh

Now configure LaunchAgent

# using sublime text editor to make this file
subl ~/Library/LaunchAgents/com.ssh-add.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>Label</key>
        <string>com.ssh-add.app</string>
        <key>Program</key>
        <string>/Users/kyleparisi/scripts/startup/ssh-add.sh</string>
        <key>RunAtLoad</key>
        <true/>
    </dict>
</plist>

Note the program string above should reflect your user. Make sure you try running it first. Now every time you login, you no longer need to think about adding ssh keys to your agent. You could do other things like run docker system prune commands, archive your desktop files, mount a network file system, whatever! Enjoy!

Comments 4 total

  • Tillman Jex
    Tillman JexSep 24, 2022

    Unfortunately not working for me. Are any other strings user specific except for the path to script?

    • Aleksey Dolgiy
      Aleksey DolgiyNov 17, 2024

      Did you figure a way to run shell script?

      • Tillman Jex
        Tillman JexNov 18, 2024

        I think I did (I've since moved to linux), but I was then having problems with getting environment variables into the launch agent. If you're just wanting to avoid the problem from the actual post (ssh not remembering ssh credentials), then look at the UseKeychain and AddKeysToAgent configuration variables for ssh.

        • Aleksey Dolgiy
          Aleksey DolgiyNov 18, 2024

          No, my problem is different. I want to start QMK HID Host automatically

          Btw, thanks!

Add comment