Adding a startup script on Big Sur [duplicate]

Solution 1:

Don't have macOS Big Sur yet; however, in previous version of macOS there is System Preferences > Users & Groups > you > Login Items, or use a Launch Agent. (I assume these methods are still available in macOS Big Sur.)

Have a look at:

  • Open items automatically when you log in on Mac

  • Creating Launch Daemons and Agents

  • See also the manual pages for launchd and launchctl in Terminal.

    • You can read the manual page for command in Terminal by typing command and then right-click on it and select: Open man Page

Update:

To refute the claim made by Vihung in a comment: "While you answer, in general, is correct, it doesn't apply to shell scripts"

The example AppleScript code, show below, used as a shell script with a #!/usr/bin/osascript shebang, and added to the Login Items tab of my account in System Preferences > Users & Groups, opens a new window in Terminal with an ssh session to another computer and automatically closes the original window that opened the ssh session in the new window.

This was tested under macOS Big Sur with Language & Region settings in System Preferences set to English (US) — Primary and worked for me without issue1.

  • 1Assumes necessary and appropriate setting in System Preferences > Security & Privacy > Privacy have been set/addressed as needed.

Example AppleScript code:

      Note: Change ssh user@hostname to a properly formed ssh command for your required usage.

#!/usr/bin/osascript

tell application "Terminal"
    do script "ssh user@hostname"
    delay 0.5
    close window 2
end tell
tell application "System Events"
    tell application process "Terminal"
        tell its front window
            set i to 0
            repeat until (exists button "Terminate" of sheet 1)
                delay 0.1
                set i to i + 1
                if i ≥ 30 then return
            end repeat
            click button "Terminate" of sheet 1
        end tell
    end tell
end tell

Notes:

This requires Terminal to be added to: System Preferences > Security & Privacy > Privacy > Accessibility

It also requires System Events to be checked under Terminal in: System Preferences > Security & Privacy > Privacy > Automation


Note: The example AppleScript code is just that and sans any included error handling does not contain any additional error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.