OSX用户登陆后自动运行相应shell脚本

原标题:

Launch shell script silently at login

 

In OSX I needed a shell script to execute at login. There are a few different ways to perform this so I thought it might be helpfulto document what your options are. I've switched over to Emacs which typically has a longer startup time than editors such as Vim. This is the shell script we will execute:

#!/bin/zshemacs --daemon

 Oftentimes Emacs will stay open during an entire user session of the OS, so the sooner I can launch it the better. OSX offers a few different startup options for us. First, we have Login Items available within Account Settings of the System Preference pane. We need to rename the shell script above to end in a .command file extension to allow the Login Items to execute it. This will run at login, however we will be left with a Terminal prompt visible when the script has completed. Preferably we would execute this in the background at user login. OSX manages system and user daemons via a tool called launchd. The interface to launchd is a tool called launchctl which allows for loading and unloading daemons into launchd. XML formatted plist files are used to describe operations loaded into launchctl.

<plist version="1.0">
 <dict>
   <key>Label</key>
   <string>emacs-daemon</string>
   <key>RunAtLoad</key>
   <true />
   <key>Program</key>
   <string>/Users/nickp/bin/scripts/launch-emacs-daemon.sh</string>    </dict>
</plist>

 The above file, emacs-daemon.plist needs to be saved in the ~/Library/LaunchAgents directory. As you can see the xml dictates that the launch-emacs-daemon.sh file should be executed at load, note we no longer need a .command file extension. We will now use launchctl to load our plist file.

launchctl load ~/Library/LaunchAgents/emacs-daemon.plist

 To verify that your script executed correctly lets ask launchctl to show us what is running.

launchctl list | grep emacs

 You will likely see two entries, each with three columns. Mine looks like this:

148-0x100100e80.anonymous.emacs-0emacs-daemon

 The first column is the process id, the first row shows the PID of the emacs daemon our shell script spawned. The second line is the emacs-daemon.plist job entry that executed, returning a status code of zero in the second column - success! With this setup, I can launch the emacsclient process which will attach to the daemon server and launch instantly.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值