DEV Community

Kyle Parisi
Kyle Parisi

Posted on

Running Scripts at Login MacOS

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!

Top comments (4)

Collapse
 
tjex profile image
Tillman Jex

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

Collapse
 
snoozerio profile image
Aleksey Dolgiy

Did you figure a way to run shell script?

Collapse
 
tjex profile image
Tillman Jex

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.

Thread Thread
 
snoozerio profile image
Aleksey Dolgiy • Edited

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

Btw, thanks!