Mac os startup script

Adding Startup Scripts to Launch Daemon on Mac OS X Sierra 10.12.6

Sep 2, 2017 · 3 min read

Being new to working on OS X, it has been somewhat confusing to how things work on Mac compared to that on Linux — to be completely honest it has been a painstaking journey while wrapping my head around the differences between the systems.

I intend to share my experience relating to adding start up shell scripts to the Launch Daemon on OS X Sierra. Any suggestions for a better solution is most welcome.

A good starting point to get to know about Launch Daemon Process — how to configure, troubleshoot and get some examples can be found here.

A daemon is a program running in the background without requiring user input.

Task in Hand

  1. Create an shell script file to start mariadb (for simplicity of demo)
  2. Launch the shell script file as soon as the computer boots up (i.e. without requiring the user to login)

Lets Start

S t ep 1: Create an shell script file using the terminal

Now add in the following code to the file — save and exit. This primarily checks if the mariadb service is enabled or not and then starts the service if it is stopped.

Give the script file execution permission

Step 2: Launch the shell script file as soon as the computer boots up

We now have to add the script file to the Launch Daemon process — which will run the Job as soon as the Mac is booted.

The behavior of a daemon/agent is specified in a special XML file called a property list. Depending on where it is stored it will be treated as a daemon or an agent.

Again, just to be clear between the difference between daemon/agents:

The main difference is that an agent is run on behalf of the logged in user while a daemon runs on behalf of the root user or any user you specify with the UserName key.

In Mac OS X, the Launch Daemons are stored inside

folder while the Launch Agents are inside

Now, lets create a property list file(.plist) here as root user. (Please note there are conventions in naming the plist file which is outside the scope of this article)

Configuration of the plist file will vary upon your use case. The list of properties that can be configured is again nicely illustrated under the Configuration section on launchd.info

For easier illustration, please check the following plit file and the inline commets:

Now that we have all the necessary files ready and in place, we need to add the property list file onto the launchctl as follows:

  • To permanently remove the plist to the Launch Daemon
  • Once a script is added onto the Launch Daemon it will auto-start even if the user runs the following command
  • A Gist with the source files is provided here.

Do let me know if this works for you! Any suggestion for improvement will be most appreciated.

Источник

Mac os startup script

A startup item is controlled by three things: a folder (such as /Library/StartupItems/MyItem), a shell script with the same name as the directory (such as MyItem), and a property list named StartupParameters.plist. The shell script and the property list must appear at the top level of the startup item’s folder. You can also create a Resources directory to hold localized resources, but this is not mandatory.

Читайте также:  Что такое windows lex pex

2.2.2.1. The startup script

The startup script should be a shell script with StartService( ), StopService( ), and RestartService( ) functions. The contents of /Library/StartupItems/MySQL/MySQL are shown in Example 2-3. The function call at the bottom of the script invokes the RunService( ) function from rc.common, which in turn invokes StartService( ), StopService( ), or RestartService( ), depending on whether the script was invoked with an argument of start, stop, or restart.

Example 2-3. A MySQL startup script

TIP: If you are using MySQL version 4 (in beta as of this writing), replace /usr/local/mysql/bin/safe_mysqld with /usr/local/mysql/bin/mysqld_safe.

Because it consults the settings of the $MYSQL environment variable, the startup script won’t do anything unless you’ve enabled MySQL in the /etc/hostconfig file. To do this, add the following line to /etc/hostconfig:

Mac OS X does not recognize any special connections between hostconfig entries and startup scripts. Instead, the startup script sources the /etc/rc.common file, which in turn sources hostconfig. The directives in hostconfig are merely environment variables, and the startup script checks the value of the variables that control its behavior (in this case, $MYSQL).

You can manually start, stop, and restart MySQL by invoking this script from the command line:

2.2.2.2. The property list

Example 2-4. The MySQL startup parameters as a NeXT property list

Example 2-5. The MySQL startup parameters as an XML property list

Description This is a phrase that describes the item.

Provides This is an array of services that the item provides (for example, Apache provides Web Server). These services should be globally unique. In the event that SystemStarter finds two items that provide the same service, it will start the first one it finds.

Requires This is an array of services that the item depends on. It should correspond to another item’s Provides attribute. If a required service cannot be started, the system won’t start the item.

Uses This is similar to Requires, but it is a weaker association. If SystemStarter can find a matching service, it will start it. If it can’t, the dependent item will still start.

OrderPreference The Requires and Uses attributes imply a particular order, in that dependent items will be started after the services they depend on. You can specify First, Early, None (the default), Late, or Last here. SystemStarter will do its best to satisfy this preference, but dependency orders prevail.

2. Startup 2.3. Scheduling Tasks

Copyright © 2003 O’Reilly & Associates. All rights reserved.

Источник

Daemons and Services Programming Guide

Customizing Login and Logout

This appendix describes technologies that fill very specific roles. As a rule, if your goal is to have a process running while the user is logged in, you should almost always use either a launch daemon or agent, as described in Creating Launch Daemons and Agents .

Running Agents Before Login

Most software that displays a user interface does not run prior to the user logging in. However, in some rare cases, it may be necessary to create a graphical agent that does.

By default, OS X does not allow any application to draw content prior to login. If you need to do so, your agent must call the setCanBecomeVisibleWithoutLogin: method on its windows. For more information, see the documentation for that method and the PreLoginAgents sample code.

Authentication Plug-Ins

Authentication plug-ins are the recommended way to perform tasks during the login process. An authentication plug-in executes while the user is logging in, and is guaranteed to complete before the user is allowed to actually interact with their account.

You might write an authentication plug-in if you need to programmatically reset an account to a predetermined state, perform some administrative task such as deleting caches to reduce server utilization, and so on.

Читайте также:  Как создать разделы для установки windows

To learn more about writing an authentication plug-in, read Running At Login.

Login and Logout Scripts

Important: There are numerous reasons to avoid using login and logout scripts:

Login and logout scripts are a deprecated technology. In most cases, you should use launchd jobs instead, as described in Creating Launch Daemons and Agents .

Login and logout scripts are run as root, which presents a security risk.

Only one of each script can be installed at a time. They are intended for system administrators; application developers should not use them in released software.

One way to run applications at login time is to launch them using a custom shell script. When creating your script file, keep the following in mind:

The permissions for your script file should include execute privileges for the appropriate users.

In your script, the variable $1 returns the short name of the user who is logging in.

Other login actions wait until your hook finishes executing. Therefore, your script needs to run quickly.

Use the defaults tool to install your login script. Create the script file and put it in a directory that is accessible to all users. In Terminal, use the following command to install the script (where /path/to/script is the full path to your script file):

To remove this hook, delete the property:

Use the same procedure to add or remove a logout hook, but type LogoutHook instead of LoginHook .

Note: If no plist file exists for com.apple.loginwindow , this method will not work. This file ( /var/root/Library/Preferences/com.apple.loginwindow.plist ) does not exist on a fresh installation until the user changes a login window setting (such as turning on fast user switching).

If you must install startup scripts programmatically, you should consider providing a copy of this file containing the default configuration options. Then, if the file does not exist, copy that default configuration file into place before running defaults . Again, application developers are strongly discouraged from using login or logout scripts, because only one such script may be installed.

Bootstrap or “mach_init” Daemons

In OS X v10.3, a mechanism similar to launchd was supported to allow the launching of programs either at system startup or on a per-user basis. The process involved placing a specially formatted property list file in either the /etc/mach_init.d or the /etc/mach_init_per_user.d directory. Such daemons also are sometimes referred to as mach_init daemons.

The use of bootstrap daemons is deprecated and should be avoided entirely. Launching of daemons through this process may be removed or eliminated in a future release of OS X.

If you need to launch daemons, use the launchd facility. If you need to launch daemons on versions of OS X that do not support launchd , use a startup item.

Copyright © 2003, 2016 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2016-09-13

Источник

Question: Q: Startup Scripts

I know this is a question that has been asked many times, but no matter what i do i can’t get a simpel applescript to run at startup.

I created my script:
set volume 4

Then saved it and added it to login items under my user. But when i login the script opens in the editor, as it was a text-file or a picture-file.
Then i read that the script should be saved as «run only», so i tried that. It resulted in an error from the editor, it couldn’t open the file.
So how to execute the script instead of open?

And what about bash script at startup. Where should i put them?

Thank you in advance

Mac Mini G4 Mac OS X (10.4.7)

Posted on Jul 14, 2006 4:25 AM

All replies

Loading page content

Page content loaded

Читайте также:  What linux is android based on

Save the script as an Application. No splash screen, not read-only.

Jul 14, 2006 5:01 AM

‘So how to execute the script instead of open?; — In ‘Script Editor’ select ‘Save’ (if the first time saving the code) or ‘Save As. ‘ (after editing previously saved code) to save the current script, and — via the ‘File Format:’ popup menu — select ‘Application’.

Place your ‘bash’ scripts in the ‘/usr/bin/’ or ‘/user/sbin/’ folders.

Note:
The ‘Run only’ check box, if check marked — will save a script or application (actually called an ‘AppleScript applet’) such that when the script or applet file is dragged onto, or opened via, ‘Script Editor’ — the respective script’s or applet’s code is not visible.

Jul 14, 2006 5:16 AM

Oops, sorry, I’m a dingbat. Meant «run-only», not «read-only»

Jul 14, 2006 7:18 AM

Perfect. I was wondering how hard it could be. 🙂

Regarding bash scripts. I want my alias commands set in the terminal. I tried with a .bashrc or .bash_rc as in Linux, but it doesn’t seem to work. So is there a ways where i can call a bash script at login to set my aliases and exports.

Jul 14, 2006 7:49 AM

‘bashrc’ is located in ‘/private/etc/’.

Place a copy of ‘bashrc’ on your ‘Desktop’ and modify it.

When finish editing the ‘Desktop’ copy of ‘bashrc’ — in ‘Terminal’, enter ‘sudo bash’ and , enter an optional password and / or then . Then enter .

mv $HOME/Desktop/bashrc /private/etc/; chmod 644 /private/etc/bashrc; chown root /private/etc/bashrc; chgrp wheel /private/etc/bashrc

. and press the key.

Once a new ‘Terminal’ window is opened the assigned alias’es and export’s should be available.

Jul 15, 2006 4:57 AM

>’bashrc’ is located in ‘/private/etc/’.

Anything in /private/etc is going to be global, not per user, so if you change that it’ll apply to every user, not just the current user.

In order to use a private .bashc file you need to make sure that your shell is bash, which isn’t necessarily the case. Other candidates for your startup files are .login, .profile .cshrc, .bash_profile and .tcshrc (amongst others) depending on what your shell is.

Lastly, shell-specific startup files won’t be applied when you log in at the GUI anyway — they’ll only be applied when you log in via that shell (e.g. in Terminal.app or vis ssh), so any bash-specific files aren’t going to do what you want.

Jul 15, 2006 1:44 PM

Unless otherwise stated, all entries are in ‘Terminal’.

01. Create a ‘.bashrc’ file in the ‘current’ $HOME folder. Enter .

and press the key.

/.bashrc’ file. For example, enter .

. and press the key. ‘TextEdit’ or some other text editor should launch and display a blank document. Make sure the text editor is in ‘text’ or ‘plain text’ mode (and not ‘rtf’, as may be with ‘TextEdit’). For this example, enter .

# ‘alias’es .
alias la=»ls -la»
alias dog=»osascript -e ‘say \»Woof woof\»‘»

. and save the document.

03. Select ‘Terminal’s ‘Terminal’, ‘Preferences. ‘ menu item, click on the ‘Execute this command (specify complete path):’ radio button, and change the listed ‘/bin/bash’ text entry to .

. and close the ‘Terminal Preferences’ window (via the red Crayola crayon button).

04. Create a ‘Terminal’ shell (‘File’, ‘New Shell’ menu item, or ‘Command N’) and enter, ‘dog’, and then ‘la’.

05. Quit ‘Terminal’, then launch (open, run) ‘Terminal’ — and try ‘dog’, and then ‘la’ again.

If you create and edit a ‘.bashrc_profile’ file, which may then include, at least .

# Get the aliases and functions
if [ -f

. then repeat Step 03 above with .

. in place of ‘/bin/bash —init-file

/.bashrc’, again — the ‘la’ and ‘dog’ commands should then work.

Anytime you modify and save the ‘.bashrc’ file, the changes will only be reflected in any new ‘Terminal’ shell(s) created.

Источник

Оцените статью