MacOS下添加自啟動腳本有很多方法, 在一篇知乎文章中了解到Launchd替代了過去的init, rc, init.d, rc.d, SystemStarter, inted/xinetd, watchdogd等, 建議用Launchd.
當(dāng)然還有別的Automator, Apple Script等方式(底層未研究), 感興趣的自己搜索, 我選擇了直接Launchd, 結(jié)合so上的這篇文章:
- 編寫自己的腳本, 添加可執(zhí)行權(quán)限
chmod a+x myscript.sh - 編寫Launchd配置文件(
.plist文件) - 結(jié)合上述兩篇文章, 確定在系統(tǒng)啟動還是用戶啟動時運行腳本, 我選擇的是用戶目錄(
~/Library/LaunchAgents/) - load這個配置:
launchctl load -w ~/Library/LaunchAgents/com.service.name.plist - 登入登出測試, 或:
launchctl start com.service.name
注:
- 可執(zhí)行腳本里的路徑有空格需要轉(zhuǎn)義
- 但plist文件里
<string>標(biāo)簽里的目錄如果有空格, 不需要轉(zhuǎn)義 -
load帶-w參數(shù)參見這篇文章 - 如果出錯, 運行
Console應(yīng)用查看日志, 或參考這篇文章, 定向日志輸出文件
即在.plist文件里添加:
<key>StandardOutPath</key>
<string>/var/log/mylog.log</string>
附: .plist文件示例
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.service.name</string>
<key>ProgramArguments</key>
<array>
<string>/path/to/my/script.sh</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
如果執(zhí)行的腳本就一句話, 你可能希望直接在.plist文件里運行, 而不是額外再多生成一個腳本吧? (source)
<key>ProgramArguments</key>
<array>
<string>/bin/bash</string>
<string>-c</string>
<string>ls -1 | grep *.txt | echo > allTextFiles</string>
</array>
繼續(xù), 如果還想以root來執(zhí)行腳本, 綜合起來, 我的實現(xiàn)如下:
cp com.run.udp2raw.plist /Library/LaunchDaemons
cd /Library/LaunchDaemons
sudo launchctl load -w com.run.udp2raw.plist
sudo launchctl start com.run.udp2raw
其中udp2raw對應(yīng)的命令是需要root權(quán)限的, 實測通過. 我選擇的是/Library/LaunchDaemons/
注: 唯一要注意的地方, 就是最后兩行,
load和start命令都需要加sudo. 沒有加的時候沒有報錯, 但是沒有運行成功.
附: folders and usage
|------------------|-----------------------------------|---------------------------------------------------|
| User Agents | ~/Library/LaunchAgents | Currently logged in user
|------------------|-----------------------------------|---------------------------------------------------|
| Global Agents | /Library/LaunchAgents | Currently logged in user
|------------------|-----------------------------------|---------------------------------------------------|
| Global Daemons | /Library/LaunchDaemons | root or the user specified with the key UserName
|------------------|-----------------------------------|---------------------------------------------------|
| System Agents | /System/Library/LaunchAgents | Currently logged in user
|------------------|-----------------------------------|---------------------------------------------------|
| System Daemons | /System/Library/LaunchDaemons | root or the user specified with the key UserName
|------------------|-----------------------------------|---------------------------------------------------|