我可以使用 cron 或 launchd 来运行 bash 脚本而无需登录吗?

我可以使用 cron 或 launchd 来运行 bash 脚本而无需登录吗?

我想运行一个简单的 bash 脚本(无论是否有人登录),类似于在 Linux 上执行/etc/cron.daily/,但在 Mac OS X Mountain Lion 10.8.4 上。如果可能的话,怎么做?它所需要做的就是复制(也许bzip)一个文件。

答案1

使用 cron,你可以用例如 来编辑超级用户的 crontab EDITOR=nano sudo crontab -e。当我尝试添加类似 的行时* * * * * say aa,即使在我退出登录窗口后,say 命令仍会运行。

使用 launchd,保存如下属性列表/Library/LaunchAgents/test.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>test</string>
  <key>ProgramArguments</key>
  <array>
    <string>say</string>
    <string>bb</string>
  </array>
  <key>StartInterval</key>
  <integer>10</integer>
</dict>
</plist>

然后运行sudo chown root /Library/LaunchAgents/test.plist​​和sudo launchctl load /Library/LaunchAgents/test.plist。当我退出登录窗口时,launchd 调度的 say 命令也会运行。

答案2

Cron 已正式弃用,因此您应该使用 launchd。

苹果上有一个教程:https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html

解释将 plist 文件放在哪里的一个很好的起点

https://alvinalexander.com/mac-os-x/mac-osx-startup-crontab-launchd-jobs

更多详细信息请访问

http://www.launchd.info

有两件事令我困惑/困惑:

1)注意 Program 和 ProgramArgments 的区别

2)如果您要运行的作业是一个脚本,它需要具有#!/bin/sh,否则 launchd 无法启动它,最终您会得到令人困惑的退出/状态代码 78。

相关内容