Aud*_*o01 11 macos bash shell system-shutdown shutdown-hook
有没有办法只在关机时运行脚本?
我的意思是,只有当计算机真正关闭到关闭状态时.仅执行注销或重新启动时,不应运行此脚本.
fre*_*dev 18
几天前我在github上发布了一个能够在启动/关闭时执行的配置/脚本.
基本上在Mac OS X上你可以/应该使用System wide and per-user daemon/agent configuration file
(plist)和bash脚本文件.这是您可以使用的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>boot.shutdown.script.name</string>
<key>ProgramArguments</key>
<array>
<string>SCRIPT_PATH/boot-shutdown.sh</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardOutPath</key>
<string>LOG_PATH/boot-shutdown.log</string>
<key>StandardErrorPath</key>
<string>LOG_PATH/boot-shutdown.err</string>
</dict>
</plist>
Run Code Online (Sandbox Code Playgroud)
您可以将此文件放入/Library/LaunchDaemons
.有许多目录可以放置plist文件,它取决于您需要什么,进程的权限等等.
~/Library/LaunchAgents Per-user agents provided by the user.
/Library/LaunchAgents Per-user agents provided by the administrator.
/Library/LaunchDaemons System wide daemons provided by the administrator.
/System/Library/LaunchAgents Mac OS X Per-user agents.
/System/Library/LaunchDaemons Mac OS X System wide daemons.
Run Code Online (Sandbox Code Playgroud)
boot-shutdown.sh
每次启动/关闭时都会加载并执行此脚本.
#!/bin/bash
function shutdown()
{
# INSERT HERE THE COMMAND YOU WANT EXECUTE AT SHUTDOWN OR SERVICE UNLOAD
exit 0
}
function startup()
{
# INSERT HERE THE COMMAND YOU WANT EXECUTE AT STARTUP OR SERVICE LOAD
tail -f /dev/null &
wait $!
}
trap shutdown SIGTERM
trap shutdown SIGKILL
startup;
Run Code Online (Sandbox Code Playgroud)
然后调用launchctl
加载和卸载守护进程/代理的命令.
sudo launchctl load -w /Library/LaunchDaemons/boot-shutdown-script.plist
Run Code Online (Sandbox Code Playgroud)